【发布时间】:2011-02-24 08:54:25
【问题描述】:
在 jQuery 中,我试图仅选择 a 和 b 的文本值为 64 的挂载节点并相应地“测试”。如果不存在 64 和“测试”,我也想回退到 32。不过,我在下面的代码中看到的是,正在返回 32 安装而不是 64。
XML:
<thingses>
<thing>
<a>32</a> <-- note, a here is 32 and not 64 -->
<other>...</other>
<mount>sample 1</mount>
<b>test</b>
</thing>
<thing>
<a>64</a>
<other>...</other>
<mount>sample 2</mount>
<b>test</b>
</thing>
<thing>
<a>64</a>
<other>...</other>
<mount>sample 3</mount>
<b>unrelated</b>
</thing>
<thing>
<a>128</a>
<other>...</other>
<mount>sample 4</mount>
<b>unrelated</b>
</thing>
</thingses>
不幸的是,我无法控制 XML,因为它来自其他地方。
我现在做的是:
var ret_val = '';
$data.find('thingses thing').each(function(i, node) {
var $node = $(node), found_node = $node.find('b:first:is(test), a:first:is(64)').end().find('mount:first').text();
if(found_node) {
ret_val = found_node;
return;
}
found_node = $node.find('b:first:is(test), a:first:is(32)').end().find('mount:first').text();
if(found_node) {
ret_val = found_node;
return;
}
ret_val = 'not found';
});
// expected result is "sample 2", but if sample 2's parent "thing" was missing, the result would be "sample 1"
alert(ret_val);
对于我正在使用的“:is”选择器:
if(jQuery){
jQuery.expr[":"].is = function(obj, index, meta, stack){
return (obj.textContent || obj.innerText || $(obj).text() || "").toLowerCase() == meta[3].toLowerCase();
};
}
必须有比我的做法更好的方法。我希望我可以用“AND”或其他东西代替“,”。 :)
任何帮助将不胜感激。谢谢!
【问题讨论】:
标签: jquery xml jquery-selectors xml-parsing