Javascript 如何从 jQuery 的父级中选择所有子级(在任何级别)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7648761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select ALL children (in any level) from a parent in jQuery?
提问by markzzz
I have to .unbind()
all elements from a parent node.
我必须.unbind()
从父节点获取所有元素。
How can I select all children (at any level) from a parent?
如何从父母中选择所有孩子(任何级别)?
Tried :
试过:
$('#google_translate_element *').unbind('click');
but it works only for the first children's level...
但它只适用于第一个孩子的水平......
Herethere is a test case
这里有一个测试用例
回答by Konerak
Use jQuery.find()to find children more than one leveldeep.
使用jQuery.find()查找深度超过一层的子级。
The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.
.find() 和 .children() 方法是相似的,除了后者只沿着 DOM 树向下移动一层。
$('#google_translate_element').find('*').unbind('click');
You need the '*'
in find()
:
你需要'*'
在find()
:
Unlike in the rest of the tree traversal methods, the selector expression is required in a call to .find(). If we need to retrieve all of the descendant elements, we can pass in the universal selector '*' to accomplish this.
与树遍历方法的其余部分不同,在调用 .find() 时需要选择器表达式。如果我们需要检索所有后代元素,我们可以传入通用选择器“*”来完成此操作。
回答by Nicola Peluchetti
I think you could do:
我认为你可以这样做:
$('#google_translate_element').find('*').each(function(){
$(this).unbind('click');
});
but it would cause a lot of overhead
但这会导致很多开销
回答by Zoup
It seems that the original test case is wrong.
看来原来的测试用例是错误的。
I can confirm that the selector #my_parent_element *
works with unbind()
.
我可以确认选择器#my_parent_element *
与unbind()
.
Let's take the following html as an example:
我们以下面的html为例:
<div id="#my_parent_element">
<div class="div1">
<div class="div2">hello</div>
<div class="div3">my</div>
</div>
<div class="div4">name</div>
<div class="div5">
<div class="div6">is</div>
<div class="div7">
<div class="div8">marco</div>
<div class="div9">(try and click on any word)!</div>
</div>
</div>
</div>
<button class="unbind">Now, click me and try again</button>
And the jquery bit:
和 jquery 位:
$('.div1,.div2,.div3,.div4,.div5,.div6,.div7,.div8,.div9').click(function() {
alert('hi!');
})
$('button.unbind').click(function() {
$('#my_parent_element *').unbind('click');
})
You can try it here: http://jsfiddle.net/fLvwbazk/7/
你可以在这里试试:http: //jsfiddle.net/fLvwbazk/7/