JQuery语法 - remove()不适用于元素

时间:2013-12-11 15:40:32

标签: javascript jquery

我需要删除容器中的特定元素(如果存在)。下面的代码警告告诉我该元素存在但无论出于何种原因,不会删除,并且oes不提供任何错误消息。

var second_page_item = $('DIV#discount_0 > .element .first_static .second_page .isotope-item');
if($(second_page_item).length == 0) {
    alert('it here');
    $(second_page_item).remove(); //WHY DOESNT IT REMOVE?
}

3 个答案:

答案 0 :(得分:3)

所以,如果它......

if($(second_page_item).length == 0) {

....没有长度,并且不存在,将其删除

$(second_page_item).remove();

很有道理,但没有什么可以删除的?

答案 1 :(得分:1)

second_page_item已经是一个jQuery对象,因此没有理由再次运行jQuery。此外,length为0意味着它不存在。这是对您的代码版本更合理的方法。

var second_page_item = $('DIV#discount_0 > .element .first_static .second_page .isotope-item');
if ( second_page_item.length > 0 ) {
  second_page_item.length.remove();
}

但是,你可以做到。

$('DIV#discount_0 > .element .first_static .second_page .isotope-item').remove();

答案 2 :(得分:0)

应该有效:

if($(second_page_item).length > 0) {
    alert('it here');
    $(second_page_item).remove();
}