[英]Selecting a nested element by id or class with jquery
I'm a bit confused how jquery searches through the DOM. 我有点困惑jquery如何通过DOM搜索。 Does it select from the root node, similar to XPath / selector, or from the current no matter where they are, similar to XPath // selector?
它是从根节点(类似于XPath /选择器)还是从当前节点(无论它们在何处)(类似于XPath //选择器)进行选择?
I have the following setup: 我有以下设置:
<body>
<div id="contentSection">
//A bunch of nested DIVs follow
<div id="parentDIV">
<span>Selector1</span>
<select class="selector" id="first">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<span>Selector2</span>
<select class="selector" id="second">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</div>
</div>
<div id="someOtherDIVs> </div>
<div id="someOtherDIVs> </div>
</body>
Now if I try to select the content section first, then filter by class or id, I can attach an event handler to the select element, but if I try to query the element directly, the event handler is never attached. 现在,如果我尝试先选择内容部分,然后按类或ID进行过滤,则可以将事件处理程序附加到select元素,但是如果我尝试直接查询该元素,则永远不会附加事件处理程序。
For example, this works: 例如,这有效:
$('#contentSection').change('.plotSelector', function(e)
But these do not: 但是这些不:
$('#first').change(function(e) ...
$('.selector').change(function(e) ...
Can someone explain why? 有人可以解释为什么吗? Is there a way to select from the root any element anywhere in the DOM?
有没有办法从根中选择DOM中任何位置的任何元素?
Using jquery 2.1.1 使用jQuery 2.1.1
Yes the selectors work across the DOM ( http://api.jquery.com/category/selectors/ ) 是的,选择器可跨DOM工作( http://api.jquery.com/category/selectors/ )
The fiddles supplied in the comments work, have you checked your console for errors, maybe the javascript isn't running completely. 注释中提供的小提琴有效,您是否检查过控制台是否有错误,可能是javascript不能完全运行。
Is there a way to select from the root any element anywhere in the DOM?
有没有办法从根中选择DOM中任何位置的任何元素?
So long as you start from document.
只要您从
document.
开始document.
, the standard javascript methods all select from the root: , 所有标准javascript方法都可以从根目录中进行选择:
document.getElementById('');
document.getElementsByClassName('');
document.getElementsByTagName('');
document.querySelector('');
document.querySelectorAll('');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.