首页 > 解决方案 > JQuery 传递元素以加载结果函数

问题描述

在使用 JQuery 加载函数加载内容 div 后,我试图垂直调整手风琴面板的尺寸,但该面板在函数内部未定义。有什么问题吗?

$(panel).load(url, data, function (result) {
    $(panel).style.maxHeight = $(panel).scrollHeight + "px";
});

标签: jquery

解决方案


您的代码中有几个问题

$(panel).style.maxHeight

无效,因为$()它是一个 jQuery 对象并且没有style属性。您可以通过$().get(0)$()[0]或直接使用来访问 JS 的元素this

$(panel)(在您的具体情况下)只有在您之前这样做时才有效var panel = "#panel"
而且您应该确保您已准备好在文档中,或者您的代码位于结束</body>标记之前。

这是重制版:

jQuery(function($) { // DOM ready and $ alias in scope

  var url = "foobar.html";
  var data = {};
  var $panel = $("#panel"); // cache your selectors

  $panel.load(url, data, function(result) {
    $(this).css("max-height", $(this).prop("scrollHeight") );
  });

});

或者 - 使用 JS 的this(元素引用对象)

jQuery(function($) { // DOM ready and $ alias in scope

  var url = "foobar.html",
      data = {},
      $panel = $("#panel");

  $panel.load(url, data, function(result) {
    this.style.maxHeight = this.scrollHeight;
  });

});

在 afunction中,您可以参考$panelusing $(this)
如果你使用ES6 语法和箭头函数,你可以使用缓存的$panel引用:

jQuery($ => { // DOM ready and $ alias in scope

  const url = "foobar.html",
    data = {},
    $panel = $("#panel");

  $panel.load(url, data, result => {
    $panel.css("max-height", $panel.prop("scrollHeight") );
  });

});

推荐阅读