0

问题:

如果元素中没有 DOM,我正在尝试触发.click()事件。<ul></ul>

这段代码背后的思考过程是,当用户点击xitem 时向左滑动,然后是.remove()从 DOM 中。由于我精美的空白 HTML,它在ul静止中留下了换行符和间距。因此,我无法让if()语句正常运行。

即使通过使用$.trim()然后比较它仍然不会触发.click()事件。

HTML 的图片

在此处输入图像描述

HTML

    <div class="btn-group pull-right nav-notice">
      <span class="badge badge-info nav-notice-button">8</span>
      <div class="notice-container">
        <span class="notice-arrow"></span>
        <ul class="notice-container-list">
          <li><span class="label label-warning">Warning</span><span class="notice-message">Warning 12315125</span><i class="notice-remove icon-remove-circle"></i></li>
          <li><span class="label label-success">success</span><span class="notice-message">Warning 12315125</span><i class="notice-remove icon-remove-circle"></i></li>
          <li><span class="label label-important">important</span><span class="notice-message">Warning 12315125</span><i class="notice-remove icon-remove-circle"></i></li>
        </ul>
      </div>
    </div>

jQuery

//live(), looking for past/present DOM
$('.notice-remove').live( "click", function(){
    //no double dipping!
    $this = $(this);
    //Hide the x item, improves the animation a bit
    $this.hide();
    //animate the width of the li, to give it a slideoff effect
    //when the animate completes, remove the element from the DOM
    $this.parent('li').animate({
        width: "0"
    }, 'fast', '',
    function(){
        $(this).remove();
    });
    //get the html contents of the ul element
    var str = $('.notice-container-list').html();
    //trim the contents of the ul, and if they are exactly empty
    //fire the click event to close the container
    if( $.trim(str) === "" ){
        log('Closing the Notice');
        $('.nav-notice-button').click();
    }
});
4

2 回答 2

1

我怀疑它会以这种方式工作。看,在为它声明一些动画功能之后,您正在检查该元素。但是该函数不会立即被调用——这就是 animate() 的全部意义所在!反过来,这意味着当您检查<ul>内容时,它仍然不是空的。

请改用以下技术:<ul> 删除时 <li>检查剩余的元素数量;如果它们都没有,请删除它<ul>本身:

$this.parent('li').animate({
        width: "0"
    }, 'fast', '',
    function(){
        var $li = $(this);
        if (! $li.siblings().length) {
           $li.parent().remove();
        }
        else {
           $li.remove();
        }
    });

这是一个有效的jsFiddle(必须在里面放一些文字<i></i>,不能使用你的 css 图标)。出于同样的原因,我使用 simple.parent().remove()而不是触发$('.nav-notice-button').click(),因为我不知道该点击应该做什么。)

于 2012-06-22T07:18:44.383 回答
0

简单地检查是否.notice-container-list有零个孩子而不是检查它的.html()?

于 2012-06-22T07:17:35.270 回答