jQuery的功能追加后没有响应() [英] jQuery functions not responding after append()

查看:103
本文介绍了jQuery的功能追加后没有响应()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一系列的格框,让用户添加/ jQuery的每个框中删除项目。我发现后,我添加新元素到一个盒子,我已经绑定到该元素的点击功能不会响应。这里是我的大约code样子:

I'm creating a series of div boxes that lets users add/remove items from each box with jQuery. I find that after I add a new element to a box, the click function I have bound to that element will not respond. Here's roughly what my code looks like:

$(".add").click(function() {
$("#targetbox").append("<span class='remove'>This element was added</span>");
});

$(".remove").click(function() {
alert("removing");
$(this).remove();
});

如果我美元,项目p $ P-填充#targetbox,他们的点击功能作出回应。这只是动态添加的项目不给函数的回应。

If I pre-populate #targetbox with items, they respond to the click function. It's only the items that are dynamically added that do not respond to the function.

推荐答案

直接添加点击的方法来你的新追加的元素

Add the click method directly to your newly appended element

$(".add").click(function() {
    $("#targetbox").append("<span class='remove'>This element was added</span>")
    .bind("click",function(e) {
        alert("removing");
        $(this).remove();
    });
});

或使用将追加任何新的后点击事件绑定你的 .live()方法上卸下摆臂元素

Or use the .live() method that will bind the click event for you after appending any new .remove elements

$(".add").click(function() {
    $("#targetbox").append("<span class='remove'>This element was added</span>");
});

$(".remove").live("click", function() {
    alert("removing");
    $(this).remove();
});

这篇关于jQuery的功能追加后没有响应()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆