jQuery $(this)语法问题

Ben*_*Ben 1 jquery this

这是一个有效的选择器吗?如果没有,那么正确的方法是什么?

$($(this)+' childElement')....
Run Code Online (Sandbox Code Playgroud)

Jus*_*ier 7

这可能是您正在寻找的:

$('childElement', $(this))
Run Code Online (Sandbox Code Playgroud)

基本上它会childElement在当前元素的上下文中搜索,this.


有关更多信息,请参阅jQuery()函数的文档.特别是,下面的摘录解释了第二个参数以及它如何等同于使用find:

默认情况下,选择器在从文档根开始的DOM内执行搜索.但是,通过使用$()函数的可选第二个参数,可以为搜索提供备用上下文.例如,如果在回调函数中我们希望搜索元素,我们可以限制该搜索:

$('div.foo').click(function() {
  $('span', this).addClass('bar');
});
Run Code Online (Sandbox Code Playgroud)

由于我们已将span选择器限制在此上下文中,因此仅在单击的元素中的跨度将获得附加类.

在内部,选择器上下文是使用.find()方法实现的,因此$('span', this)相当于$(this).find('span').