$(“.box a”).live(“点击”如何修改它

$(".box a").live("click" how to modify it

本文关键字:何修改 修改 点击 live box      更新时间:2023-09-26

嗨,伙计们需要一点帮助。

我知道.live不再在 jQuery v1.9 中工作,我的以下函数是否有任何替代方案可以恢复工作,我尝试.on().bind()但没有成功。这是小提琴

.HTML

<div id="container">
    <p>There are 0 boxes</p>
    <a href="#" class="more">Add more +</a>
</div>

jQuery

$(".more").click(function() {
    $("#container").append("<div class='box'><a href='#'>x</a></div>");
    var count = $(".box").length;
    $("p").text("There are " + count + " boxes.");
    if(count>2){
        $(".more").hide();
    }
});
$(".box a").live("click", function() {
    $(this).parent().remove();
    var count = $(".box").length;
    $("p").text("There are " + count + " boxes.");
     if(count<3)
    {$(".more").show();}
});

对动态添加的元素使用事件委派:

http://jsfiddle.net/89wTX/11/

$(".more").on('click', function() {
    $("#container").append("<div class='box'><a href='#'>x</a></div>");
    var count = $(".box").length;
    $("p").text("There are " + count + " boxes.");
    if(count>2){
        $(".more").hide();
    }
});
$("#container").on("click", '.box a', function() {
    $(this).parent().remove();
    var count = $(".box").length;
    $("p").text("There are " + count + " boxes.");
     if(count<3)
    {$(".more").show();}
});

当您只使用on而不进行委派时,它会将侦听器附加到现有元素一次。当您添加新元素(在您的案例中为框)时,它们没有附加侦听器。

你的脚本代码应该是这个;

$(".more").click(function() {
  $("#container").append("<div class='box'><a href='#'>x</a></div>");
  var count = $(".box").length;
  $("p").text("There are " + count + " boxes.");
    if(count>2)
     {
       $(".more").hide();
     }
  $(".box a").click(function() {
  $(this).parent().remove();
  var count = $(".box").length;
  $("p").text("There are " + count + " boxes.");
    if(count<3)
     {
      $(".more").show();
     }
  });   
});

这是小提琴

TRy thishttp://jsfiddle.net/devmgs/89wTX/9/

$(document).on("click",".box a", function() {
    console.log("removeing");
    $(this).parent().remove();
    var count = $(".box").length;
    $("p").text("There are " + count + " boxes.");
     if(count<3)
    {$(".more").show();}
});

用于 :

$(".box").on("click","a", function() {...})
$(".box").on("click","a", function() {
   ....
});

参考资料