What does $(''class for the same element', element) mean?

无人久伴 提交于 2020-01-25 09:01:27

问题


I don't unterstand this syntax:

var dir = $("a.store").parents("table")[0];
var stores = $("a.store:has(b)", dir);

What will store contain?

What is the meaning of "$("a.store:has(b)", dir);"?


回答1:


It will return a collection of dom elements that match the css selector ("a.store:has(b)") that are children of the dom element stored in the 'dir' variable.




回答2:


In your example, dir is the context of the selector. From the docs linked by Felix in his comment:

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, to do a search within an event handler, the search can be restricted like so:

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



回答3:


From the jquery docs,

:has() Selector

Selects elements which contain at least one element that matches the specified selector.

The expression $('div:has(p)') matches a <div> if a <p> exists anywhere among its descendants, not just as a direct child.

http://api.jquery.com/has-selector/

Regarding the second parameter to jQuery, it is the context. It can be a DOM element on which the selector operates.

In your case: var dir will have a table which is parent of <a class="store" ...

the store variable will contain only those <a class="store" .. which have a <b> inside them.




回答4:


$("a.store")

Will get all <a> elements that have the class .store

.parents("table")[0];

Will get the table(s) these <a> reside in.

$("a.store:has(b)", dir);

Will find all <a> elements that have the class .store and contain a <b> element, using the previously found tables dir as context, meaning that instead of going through the entire document to find matches, it will only go through these tables.




回答5:


In its simplest form..

Its equivalent to doing..

$('someParent').find('.matchingDescendants');


来源:https://stackoverflow.com/questions/6479300/what-does-class-for-the-same-element-element-mean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!