2013-02-13 36 views
0

我正在使用jQuery在用户每次单击链接(“.add-event”)时动态添加元素。此元素中还包含一个图标,用于在用户选择时删除整个元素。如果元素是页面上最后一个元素,我想要隐藏或禁用此删除图标。这是我到目前为止已经试过:防止仅使用子伪选择器的默认功能

$(document).on('click','.close_box2:only-child',function(){ 
    event.preventDefault(); 
}); 

if($('.event').length===1) { 
    $('.close_box2').hide() 
} 

HTML:

<div class="event"> 
    <span class="close_box2"><i class="icon-remove"></i></span> 
    <span class="add-event">Add Event</span> 
</div> 

我在做什么错!?由于

+1

至少第二个工程:http://jsfiddle.net/KPY9r/ – 2013-02-13 20:28:07

+0

哇很好的电话,我必须有一些其他的错误或冲突在我的网页,阻止这个工作。谢谢! – Mac10 2013-02-13 20:42:57

回答

0

下看起来更好,对于性能:

$('.close_box2:only-child').on('click', function(event){ 
    event.preventDefault(); 
}); 
+0

表演在哪?这需要花费更长的时间来连接,因为它执行搜索“前端”,并导致多个处理程序,而他们使用的委托“on”以闪电般的速度将一个处理程序连接到“文档”(并且您不在意微小的延迟事件时间,因为你不能点击快速注意!):) – 2015-01-16 16:34:44

1

的jsfiddle:http://jsfiddle.net/TrueBlueAussie/KPY9r/6/

你只是要检查 “最后一个” 删除处理程序中:

// initial hide of sole close button 
$('.close_box2').hide(); 

// On add, clone the template and show all close buttons 
$(document).on('click', '.add-event', function() { 
    // Create a new event based on the template 
    $('#events').append($('#template').html()); 
    // Show all close buttons (as we must now have > 1 event) 
    $('.close_box2').show(); 
}); 

$(document).on('click', '.close_box2', function (e) { 
    $(this).closest('.event').remove(); 
    // Is there only one left? 
    if ($('.event').length === 1) { 
     // Hide the close box on the last event 
     $('.close_box2').hide() 
    } 
}); 

备注:

  • 我使用虚拟<script>元素来容纳你的HTML模板。这比克隆页面上的元素要好,并且比代码中的内嵌HTML字符串要好得多。