jQuery $(this) syntax question

2019-05-30 22:52发布

Is this a valid selector? If not, what's the correct way?

$($(this)+' childElement')....

标签: jquery this
4条回答
小情绪 Triste *
2楼-- · 2019-05-30 23:20
$(this).find('childrenSelector');
查看更多
在下西门庆
3楼-- · 2019-05-30 23:21

Use

 $(this).find("childrenSelector")
查看更多
来,给爷笑一个
4楼-- · 2019-05-30 23:26

Or...

$(this).children('.element');

查看更多
我命由我不由天
5楼-- · 2019-05-30 23:38

This may be what you are looking for:

$('childElement', $(this))

Basically it will search for childElement within the context of the current element, this.


For more information, see the documentation for the jQuery() function. In particular, the following excerpt explains the second argument and how it is equivalent to using find:

By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function. For example, if within a callback function we wish to do a search for an element, we can restrict that search:

$('div.foo').click(function() {
  $('span', this).addClass('bar');
});

Since we've restricted the span selector to the context of this, only spans within the clicked element will get the additional class.

Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').

查看更多
登录 后发表回答