1

我的脚本有点问题。我需要检查一些跨度,如果我中间有一些内容,我什么也不做......但如果它是空的,我想删除这个跨度或例如更改样式。现在,当指定跨度为空时,脚本会清除我所有的跨度,即使它们不是空的。你能帮助我吗?

html

<span class="insert_list_item"></span>
<span class="insert_list_item">data</span>

脚本

if ($('.insert_list_item').length > 0){
    $('.insert_list_item').each().remove();
} 
4

5 回答 5

4

采用:empty

$('.insert_list_item:empty').remove()

删除所有空元素。或者

 $('.insert_list_item:not(:empty)').remove()

删除所有非空元素

http://api.jquery.com/category/selectors/你可以看到所有可用的选择器。

于 2012-08-08T14:28:31.463 回答
2

每个检查长度:

$('.insert_list_item').each( function(){
     var span = $(this);
     if (span.html().length === 0) {
         span.remove();
     }
});

或者

使用 :empty: 过滤

$('.insert_list_item').filter(":empty").remove();
于 2012-08-08T14:30:10.387 回答
2

怎么样:

$( '.insert_list_item' ).filter(function () { 
    return $.trim( $( this ).text() ) === '';
}).remove();

现场演示:http: //jsfiddle.net/RMZLm/

请注意,此解决方案也适用于包含空格(例如<span class="insert_list_item"> </span>)的 SPAN 元素。

于 2012-08-08T14:30:47.293 回答
1

使用条件里面each。因为 each 遍历选择器返回的所有元素。

$('.insert_list_item').each(function(){

  if($(this).html().length === 0)
       $(this).remove();
});
于 2012-08-08T14:28:53.223 回答
0

试试这个:

if ($('.insert_list_item').text().length > 0){
    $('.insert_list_item').remove();
} 
于 2012-08-08T14:29:28.637 回答