我想在鼠标离开时向元素添加 .close
类,然后我想出于原因删除该类。
$("#nav > li").mouseleave(function (){
alert($(this).children(".subs").length); // value 1
$(this).children(".subs").addClass("close");
setTimeout(function () {
alert($(this).children(".subs").length)
}, 500); // value 0
});
添加类后我无法访问该元素。我可以做什么来完成这项工作?
操作前的 HTML:
<div class="subs" id="service-subs" aria-haspopup="false">
stuff
</div>
操作后的 HTML:
<div class="subs close" id="service-subs" aria-haspopup="false">
stuff
</div>
最佳答案
这是因为 this
变量在事件触发后变空,并且当 this
变量没有值时调用 setTimeout
函数。您可以将 this
的值存储在另一个变量中。
$("#nav > li").mouseleave(function (){
var $this = $(this);
alert($this.children(".subs").length);
$this.children(".subs").addClass("close");
setTimeout(function () {
alert($this.children(".subs").length)
}, 500);
});
关于javascript - JQuery:无法访问修改的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45647398/