I'm getting started with JQuery and javascript in general and I'm running into an issue that I'm not understanding. Assuming I have a table of data(let's say the id of the table is 'tbl') that has elements, which may or may not have an 'orderasc' class associated with it (only 1 element can have this at any one time, but none have to have it).
I can check for the existence of an element with the 'order开发者_StackOverflow中文版asc' class using the following:
if($('#tbl th').is('.orderasc')) {
//do something here
}
which works fine. Inside of the if statement, I'm trying to alert the name attribute of the element that has the 'orderasc' class. Trying the following does not work (shows undefined):
alert($('#tbl th').find('.orderasc').attr('name'));
but the following does:
alert($('#tbl').find('th.orderasc').attr('name'));
Likewise, when I modify my original if statement to this:
if($('#tbl').is('th.orderasc')) {
//do something here
}
It does not work. Can someone explain to me what's happening behind the scenes and giving me these results?
The $('#tbl th').find...
is recursively searching the DOM in the th
, however your th
is the element with the class.
To add to that the find
function is recursive, and can be expensive. At least more expensive than the children
function or using a psuedo class. I would recommend something like this instead:
alert($('#tbl th.orderasc:first').attr('name'));
jsFiddle
.find()
searches the children inside that element. since the th
has the class orderasc
your selector: $('#tbl th')
is already at the th
and the .find()
will look inside the th
for the orderasc
class.
精彩评论