我想检查特定节点是否存在并执行一组特定的指令。我在xml文件中有两个文本元素,例如,XML文件的一部分是:
<text transform="matrix(1 0 0 1 818.252 302.8809)">
<tspan x="0" y="0" font-family="'Arial-BoldMT'" font-size="14.7311">INLET</tspan>
<tspan x="-4.867" y="15.401" font-family="'Arial-BoldMT'" font-size="14.7311">FILTER</tspan>
</text>
<text transform="matrix(1 0 0 1 792.9395 64.6396)" font-family="'Arial-BoldMT'"font-size="14.7311">
COMPENSATOR
</text>
请注意,一个节点的内部包含tspan而另一个节点没有。我想做一个if语句,检查tspan节点并返回文本内部,并返回文本节点内的文本。 if语句会是什么样的?
答案 0 :(得分:1)
所有代码都有注释,因此应该很容易理解!
<强> Live demo (click). 强>
//find all "text" nodes
var $texts = $('text');
//loop through each "text" node
$texts.each(function(i, elem) {
//make a jQuery object from the node
var $text = $(elem);
//look for "tspan" children
var $tspans = $text.children('tspan');
//if there are any children
if (!$tspans.length) {
//get the "text" node's text
var text = $text.text();
console.log('No tspan: '+text);
}
else { //if there are children tspans
//loop through each tspan
$tspans.each(function(i, tspan) {
//make a jQuery object from the tspan
var $tspan = $(tspan);
//get the tspan's text
var text = $tspan.text();
console.log('From tspan: '+text);
});
}
});