如何克隆过滤的jQuery对象?

时间:2012-12-22 05:06:46

标签: javascript jquery

我使用$xml = $(xmldoc)将XML文档加载到jQuery。然后我通过$xml.filter('id="something"')过滤它。在过滤的xml上使用.index()时,jQuery会返回原始列表中的索引,而不是已过滤的列表

示例:

<xmlroot>
  <xmlnode id="1" color="blue" />
  <xmlnode id="2" color="orange" />
  <xmlnode id="3" color="blue" />
  <xmlnode id="4" color="orange" />
  <xmlnode id="5" color="blue" />
</xmlroot>

    vObject = $xml.filter('[color="orange"]'); //vObject should just receive the xmlnodes 2 and 4
    vResult = vObject.filter('[id="4"]').index();

vResult将始终为3,但应为1。

我知道这个jQuery行为是设计的,但是我需要一个解决方案来用过滤的xml来填充vObject,而不是所有的xml。我整晚都在尝试,但我没有想法。

如果这里的一位专家可以提供帮助,我们将非常高兴。 谢谢!

1 个答案:

答案 0 :(得分:2)

如果要获取jQuery集合中元素的索引,则应将该元素传递给index方法:

var vResult = vObject.index(vObject.filter('[id="4"]')); // 1    
           // vObject.index(vObject.filter('[id="2"]')); // 0
           // vObject.index(vObject.filter('[id="3"]')); // -1

http://jsfiddle.net/C9Nyg/