如何使用 JQuery 获取属性等于值的所有节点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1040817/
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 can I use JQuery to get all nodes with an attributes equal to a value?
提问by uriDium
I am getting some XML back from an AJAX call (no surprise) and I want to do something but only on certain nodes and something else on the rest. For example
我从 AJAX 调用中得到了一些 XML(毫不奇怪),我想做一些事情,但只在某些节点上,在其他节点上做其他事情。例如
<xml>
<node name="x">
</node>
<node name="x">
</node>
<node name="y">
</node>
<node name="z">
</node>
</xml>
I want all the nodes with name x to go to one table and I want all the others to go to another table.
我希望所有名称为 x 的节点都转到一个表,而我希望所有其他节点都转到另一个表。
回答by Martijn Pieters
Use an attribute filter, in particular the attributeEquals filter:
使用属性过滤器,特别是attributeEquals 过滤器:
$("node[name='x']");
To select all the other nodes, use the attributeNotEquals filter:
要选择所有其他节点,请使用attributeNotEquals 过滤器:
$("node[name!='x']");
You can then apply jQuery manipulationsto move these nodes elsewhere.
然后,您可以应用 jQuery操作将这些节点移动到其他地方。
Note that XPath-style selectors where deprecated in version 1.2, and have been removed altogether in jQuery 1.3.
请注意,XPath 样式的选择器在 1.2 版中已被弃用,而在 jQuery 1.3 中已被完全删除。
If you can influence what the server sends, you may want to switch to using JSON instead, you may find it easier to parse.
如果您可以影响服务器发送的内容,您可能希望改用 JSON,您可能会发现它更容易解析。
回答by Daniel Moura
success: function(xml) {
$(xml.find('node').each(function(){
if($(this).attr('name')=='x') {
//go to one table
} else {
//go to another table
}
}
}
回答by Fiona - myaccessible.website
You can use xpath in jQuery to select the nodes:
您可以在 jQuery 中使用 xpath 来选择节点:
$("//node[@name='x']")
$("//节点[@name='x']")
回答by Scott Baker
jQuery accepts xpath expressions as well.
jQuery 也接受 xpath 表达式。
$('node[name="x"]')
will select all the nodes named "node" with an attribute of "name" that has the value "x"
将选择所有名为“node”的节点,其属性为“name”且值为“x”