简体   繁体   English

从$ .each中的DOM中删除元素

[英]Remove elements from the DOM inside $.each

I have list of elements and on certain event I want to destroy them from the dom. 我有元素列表,在某些情况下,我想从dom中销毁它们。

if (appendedElements.length > 0) {
    $.each(appendedElements, function (i) {
        $(i).remove();
   })
}

appendedElements are of course greater than zero but I'm not deleting elements. appendedElements当然大于零,但我没有删除元素。 What's wrong with this code? 此代码有什么问题?

The problem is that the first argument of the parameter method is an index of the element, not the element itself. 问题在于参数方法的第一个参数是元素的索引,而不是元素本身。 This one is passed as a second parameter. 此参数作为第二个参数传递。 Try: 尝试:

if (appendedElements.length > 0) {
    $.each(appendedElements, function (i, element) {
        $(element).remove();
       //i = 0, 1, 2....
   })
}

The whole reference with examples you can find here: 带有示例的完整参考可以在这里找到:

http://api.jquery.com/jquery.each/ http://api.jquery.com/jquery.each/

If the appendedElements is a jQuery object or is an array of dom element references then there is no need to iterate, you can just call the remove method like 如果appendedElements是jQuery对象或dom元素引用的数组,则无需进行迭代,您可以调用remove方法,例如

$(appendedElements).remove();

As already suggested the problem is the first param to the each callback is the index of the item, not the item itself. 如前所述,问题是each回调的第一个参数是项目的索引,而不是项目本身。

if (appendedElements.length > 0) {
    $.each(appendedElements, function (i) {
        $(this).remove(); // use this
   })
}

You should use the second argument of the each callback function: 您应该使用each回调函数的第二个参数:

if (appendedElements.length > 0) {
    $.each(appendedElements, function (index, element) {
        $(element).remove();
   })
}

You can try it without .each for example if you have list... something like that 您可以不使用.each进行尝试,例如,如果您有列表...

<ul id="columar">
  <li>ok</li>
  <li>ok</li>
  <li>ok</li>
  <li>ok</li>
</ul>

if you wanna remove the li list you can wiht this code: 如果要删除列表,可以使用以下代码:

if (2 == 2) {
  $('#columar li').remove()
}

JSFiddle JSFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM