0

当我的脚本告诉我元素为空但在控制台中我可以看到元素不为空时,我遇到了小问题

第一,我充满了动态元素

$(document).on('click', '.add-color', function(e){
var name = $(this).closest('.row').find('.details').data('name');

    addHtml = '<div>';
    addHtml += '<input type="checkbox" checked name="" value="'+ name +'">';
    addHtml += '<span>'+ name +'</span>';
    addHtml += '<button type="button" class="remove"><i class="fa fa-times"></i></button>';
    addHtml += '</div>';

$(addHtml).appendTo('#product .selectedId div[data-name="'+name+'"]');
}

删除按钮事件

$(document).on('click', '.remove', function(){
if ($('.selectedId:empty')) {
                console.log('empty');
            }else {
                console.log('isnt empty');
            }

如果我将 2 个元素添加到元素“selectedId”中并删除其中一个,我会进入控制台“空”但在检查器中我可以看到还有一个元素

4

1 回答 1

0

if ($('.selectedId:empty'))将始终返回 true,因为 :empty 是一个选择器,返回的是一个类似于 jQuery 数组的结构,其中包含与您的选择器匹配的元素。将其转换为布尔值时,它始终为真。

你可能想要if ($('.selectedId:empty').length === 0)

样本:

$(document).on('click','#btnAdd', function(){
  $('#product').append('<p>something</p>');
});
$(document).on('click','#btnRemove',function(){
  if($('#product:empty').length > 0)
    alert('empty!')
  else
  {
    $('#product > p:first').remove();
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='product'></div>
<button id='btnAdd'>Add</button>
<button id='btnRemove'>Remove</button>

至于空,这是 css 的 :empty,但对于这些测试,它们是相同的结果:

$(function(){
  $('td:empty').addClass('empty');
});
td { outline: 1px solid red;}
td::after { content:'jquery not emtpy';background-color:orange; }
td:empty::before {
  content: 'css empty';
  background-color:red;
}
td:not(:empty)::before {
  content: 'css not empty';
  background-color:red;
}
td.empty::after {
  content:'jquery empty';
  background-color:orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td><span></span></td>
    <td><div></div></td>
  </tr>
  <tr>
    <td></td><td> </td>
  </tr>
  <tr>
    <td>
    </td>
    <td></td>
  </tr>
</table>

于 2019-09-19T14:16:43.783 回答