jquery - JQuery 传递元素以加载结果函数
问题描述
在使用 JQuery 加载函数加载内容 div 后,我试图垂直调整手风琴面板的尺寸,但该面板在函数内部未定义。有什么问题吗?
$(panel).load(url, data, function (result) {
$(panel).style.maxHeight = $(panel).scrollHeight + "px";
});
解决方案
您的代码中有几个问题
$(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
中,您可以参考$panel
using $(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") );
});
});
推荐阅读
- powershell - 对于由 Start-Job 运行的 powershell 运行的外部命令,没有静默选项,可以做些什么?
- azure-data-factory - Azure 数据工厂:如何更新直到活动中的条件值以退出循环
- android - React Native:水平和垂直分页一起使用
- javascript - Firebase 网络身份验证:电子邮件地址格式错误
- c# - 读入/获取 XML 的编码类型
- php - 将插入查询从 sql 文件转换为 php 数组
- java - JSON 数据未从 StringRequest 凌空转换为 JSONObject
- sql-server - 在 mssql 中运行查询会出错
- ios - ARKit 图像识别黑白
- javascript - 使用 REST 在 MS Sharepoint 的现有列表中添加新项目?