使用ID通过ID或类选择嵌套元素 [英] Selecting a nested element by id or class with jquery
问题描述
我有点困惑jquery如何搜索DOM. 是从根节点(类似于XPath/选择器)还是从当前节点(无论它们在何处)(类似于XPath//选择器)进行选择?
我有以下设置:
<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>
现在,如果我先选择内容部分,然后按类或ID进行过滤,则可以将事件处理程序附加到select元素,但是如果我尝试直接查询该元素,则永远不会附加该事件处理程序./p>
例如,这有效:
$('#contentSection').change('.plotSelector', function(e)
但是这些不是:
$('#first').change(function(e) ...
$('.selector').change(function(e) ...
有人可以解释为什么吗?有没有一种方法可以从根中选择DOM中任何位置的任何元素?
使用jquery 2.1.1
是的,选择器跨DOM工作( 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. For example, this works: But these do not: Can someone explain why? Is there a way to select from the root any element anywhere in the DOM? Using jquery 2.1.1 Yes the selectors work across the 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. 这篇关于使用ID通过ID或类选择嵌套元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!$('#contentSection').change('.plotSelector', function(e)
$('#first').change(function(e) ...
$('.selector').change(function(e) ...