当我将 jQuery 对象存储在变量中时,如下所示:
var $myObject = $("div#comments");
...我无法使用对象 $myObject!
这就是我正在做的更改 div#comments 的 html:
$myObject.html(data);
它什么也没做。我也已经尝试过这种方式,这次是在 div#comments 中选择一个元素:
$("div.comment", $myObject);
这不起作用。
我只是希望能够将元素保存在变量中,然后使用它!
注意:有些人不会在变量名前加上 $,例如:myObject。
最佳答案
您是在文档加载后调用它吗?
// This will ensure that the code doesn't run until
// the document has loaded
$(function() {
var $myObject = $("div#comments");
});
(这是 jQuery 的 .ready()
方法的快捷方式。)
只要文档加载完毕,你就有了<div>
ID 为 comments
当页面加载时,它应该可以工作。
另请记住,页面上只能有一个具有任何给定 ID 的元素。正因为如此,这样做实际上更好(更快)一点$("#comments");
而不是$("div#comments");
.
关于javascript - jQuery 对象不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3496369/