jquery:.find() 搜索的属性
我正在开始使用 JQuery 和 javascript,但我遇到了一个我不理解的问题。假设我有一个数据表(假设表的 id 是“tbl”),其中包含一些元素,这些元素可能有也可能没有与其关联的“orderasc”类(任何时候只有 1 个元素可以拥有该类,但没有人必须拥有它)。
我可以使用以下命令检查带有“orderasc”类的元素是否存在:
if($('#tbl th').is('.orderasc')) {
//do something here
}
效果很好。在 if 语句内部,我试图提醒具有“orderasc”类的元素的 name 属性。尝试以下方法不起作用(显示未定义):
alert($('#tbl th').find('.orderasc').attr('name'));
但以下方法起作用:
alert($('#tbl').find('th.orderasc').attr('name'));
同样,当我将原始 if 语句修改为:
if($('#tbl').is('th.orderasc')) {
//do something here
}
它不起作用。 有人可以向我解释幕后发生的事情并给我这些结果吗?
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 'orderasc' 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
$('#tbl th').find...
正在递归搜索th
中的 DOM,但是您的th
是元素与班级。除此之外,
find
函数是递归的,并且可能很昂贵。至少比children
函数或使用伪类更昂贵。我会推荐这样的东西:jsFiddle
The
$('#tbl th').find...
is recursively searching the DOM in theth
, however yourth
is the element with the class.To add to that the
find
function is recursive, and can be expensive. At least more expensive than thechildren
function or using a psuedo class. I would recommend something like this instead:jsFiddle
.find()
搜索该元素内的子元素。由于th
具有类orderasc
您的选择器:$('#tbl th')
已经位于th
> 并且.find()
将在第th
内部查找orderasc
类。.find()
searches the children inside that element. since theth
has the classorderasc
your selector:$('#tbl th')
is already at theth
and the.find()
will look inside theth
for theorderasc
class.