gpt4 book ai didi

jquery - 使用 jQuery .each 和 $(this) 删除 XML 节点

转载 作者:数据小太阳 更新时间:2023-10-29 01:56:44 24 4
gpt4 key购买 nike

我正在使用 jQuery 的 .each() 遍历一些元素,并且我想在满足特定要求时删除一个节点。我不确定这个的语法,我尝试了几件事:

$(this).remove();
$xml.remove(this);
$xml.removeNode(this);

...等等在找到一个有效的例子时遇到了一些麻烦,有人可以指出我正确的方向吗?我假设它很简单,我只是找不到正确的语法。下面有一个不工作的 fiddle 。

http://jsfiddle.net/SHNpn/

谢谢

最佳答案

那是因为对 remove() 的调用只会从 DOM 中删除元素。它不会从您的 $siblings jQuery 对象中删除它。

如果在移除alex 节点后再次调用find() 重新匹配 sibling ,您将得到预期的结果:

var $xml = $(xmlString);
var $siblings = $xml.find("sibling");

$siblings.each(function(){
var name = $(this).attr("name");
if (name == "alex")
$(this).remove();
});

// Here, the "alex" element is not in the DOM, but still part of $siblings.

$xml.find("sibling").each(function(){
var name = $(this).attr("name");
console.log(name);
});

// Since we're calling find() again, the code above will only print "bob".

你会发现一个更新的 fiddle here .

关于jquery - 使用 jQuery .each 和 $(this) 删除 XML 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8065775/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com