jQuery 选择器选中某节点,在后续的链式操作函数内使用 $(this) 的结果是 Window 对象,而非该节点对象

2022-10-17,,,,

<ul class="tree-ocx">
<li class="tree-ocx-li" data-displayed="false">
<div class="tree-ocx-tip">分类</div>
<ul class="tree-ocx-body">
<li class="sub-category-item">设计作品</li>
<li class="sub-category-item">技巧杂烩</li>
<li class="sub-category-item">生活随笔</li>
</ul>
</li>
</ul>

当我们使用 JQ 选择器选中节点 A 之后,并为之添加点击事件on(events, hander)。hander 参数接收一个箭头函数,在箭头函数中又需要选中此节点 A,为其添加一个 CSS 样式。$(this)的 this 指向的并不是节点 A,而是Window对象

$(".tree-ocx-li").on("click", () => {
$(this).addClass("tree-ocx-li-active");
}

箭头函数箭头函数 - JavaScript | MDN没有自己的 this、arguments、super。所以,在箭头函数里面使用 this,其实就是 Window 对象。

把箭头函数换成普通函数,此时的this就是函数本身,普通函数有箭头函数没有的东西,例如 arguments、super。普通函数可以使用 new,即构造器:

$(".tree-ocx-li").on("click", function () {
$(this).addClass("tree-ocx-li-active");
}

jQuery 选择器选中某节点,在后续链式操作函数内使用 $(this) 的结果是 Window 对象,而非该节点对象的相关教程结束。

《jQuery 选择器选中某节点,在后续的链式操作函数内使用 $(this) 的结果是 Window 对象,而非该节点对象.doc》

下载本文的Word格式文档,以方便收藏与打印。