我希望能够选择一组特定的子项,其中定义了一个属性。
但是如何选择具有属性 data-role
的根选择器的第一个子节点的子节点?
first-of-type
由于元素的类型,选择器不起作用。
这里有一个 DOM 示例。
<body>
<div data-role="ca:panel" title="foo">
<div data-role="ca:vbox" width="100%">
<div data-role="ca:form">
<div data-role="ca:formitem">
<div data-role="ca:hbox">
<input data-role="ca:textinput">
<div data-role="ca:menu"></div>
</div>
</div>
<div data-role="ca:formitem">
<input data-role="ca:passwordinput">
</div>
<div data-role="ca:formitem">
<select data-role="ca:combobox">
<option>[...]</option>
</select>
</div>
</div>
<table>
<tbody>
<tr>
<td>
<span data-role="ca:label"></span>
</td>
<td>
<button data-role="ca:button"></button>
</td>
<td>
<button data-role="ca:button"></button>
</td>
</tr>
</tbody>
</table>
</div>
</body>
我的过滤器应该只选择
-
<div data-role="ca:form">
-
<span data-role="ca:label"></span>
-
<button data-role="ca:button"></button>
-
<button data-role="ca:button"></button>
它应该在任何情况下都有效,意思是,它不应该链接到 dom 的特定结构并且必须使用数据 Angular 色作为“选择器”。
我不是相关的 jQuery 开发人员。我尝试了一些选择器,例如 $('[data-role]:first-of-type');
但它不起作用。
您有选择合适 child 的想法吗?
注意:找到第一个 parent 不是问题。
最佳答案
只要您有一个起始节点,就可以使用过滤器一般地执行此操作:
JS过滤器:http://jsfiddle.net/TrueBlueAussie/2uppww9s/5/
var root = $('[data-role="ca:vbox"]');
var matches = root.find('[data-role]').filter(function(){
return $(this).parentsUntil(root, '[data-role]').length == 0;
});
alert(matches.length);
关于javascript - 根据属性选择第一个 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26161264/