<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">

        $(document).ready(function() {

            $("button").click(function() {
                $("h2").html("<p class='test'>click me</p>")
            });   

            $(".test").click(function(){
                alert();
            });
        });

    </script>
</head>
<body>
    <h2></h2>
    <button>generate new element</button>
</body>
</html>

我试图通过单击按钮在<h2>中生成一个类名为test的新标记。我还定义了一个与test关联的单击事件。但是这个事件不起作用。

有人能帮忙吗?


当前回答

对委托事件使用.on()方法

$('#staticParent').on('click', '.dynamicElement', function() {
    // Do something on an existent or future .dynamicElement
});

.on()方法允许你将任何想要的事件处理程序委托给: 当前元素或将来添加到DOM的元素。

注:不要使用.live()!从jQuery 1.7+开始,.live()方法已弃用。

其他回答

另一种更简洁的方法(IMHO)是使用一个原始的javascript函数来响应一个on click事件,然后将目标元素传递回jQuery。这种方法的优点是你可以在任何地方动态地添加你的元素,点击处理程序将“正常工作”,你不需要担心把控制委托给父元素,等等。

步骤1:更新动态html以触发onclick事件。确保将'event'对象作为参数传递


    $("button").click(function() {
        $("h2").html("<p class='test' onclick='test(event)'> click me </p>")
    });

步骤2:创建测试函数以响应单击事件


    function test(e){
        alert();
    });

可选步骤3:鉴于您正在使用jQuery,我假设它将有用的引用返回到源按钮


    function test(e){
        alert();

        // Get a reference to the button
        // An explanation of this line is available here
        var target = (e.target)? e.target : e.srcElement;

        // Pass the button reference to jQuery to do jQuery magic
        var $btn = $(target);

    });

您正在使用的click()绑定称为“直接”绑定,它只会将处理程序附加到已经存在的元素上。它不会与将来创建的元素绑定。为此,您必须使用on()创建一个“委托”绑定。

委托事件的优点是,它们可以处理来自稍后添加到文档的后代元素的事件。

以下是你想要的:

Var计数器= 0; $("按钮").click(函数(){ 美元(h2)。追加(“< p class = '测试' >点击我”+(+ +计数器)+ " < / p > ") }); // on(): 美元(h2)。On ("click", "p.test", function(){ 警报($(这)。text ()); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js " > < /脚本> < h2 > < / h2 > 生成新的元素</button>

以上内容适用于使用jQuery 1.7+版本的用户。如果你使用的是旧版本,请参考下面之前的答案。


之前的回答:

尝试使用live():

$("button").click(function(){
    $("h2").html("<p class='test'>click me</p>")
});   


$(".test").live('click', function(){
    alert('you clicked me!');
});

为我工作。尝试用jsFiddle。

或者用delegate()有一种新奇的方法:

$("h2").delegate("p", "click", function(){
    alert('you clicked me again!');
});

更新的jsFiddle。

你需要使用.live来工作:

$(".test").live("click", function(){
   alert();
});

或者如果你使用jquery 1.7+使用.on:

$(".test").on("click", "p", function(){
   alert();
});

你可以点击添加动态创建的元素。下面的例子。使用“何时”来确保完成。在我的例子中,我用类扩展抓取了一个div,添加了一个“点击查看更多”的跨度,然后使用这个跨度隐藏/显示原始的div。

$.when($(".expand").before("<span class='clickActivate'>Click to see more</span>")).then(function(){
    $(".clickActivate").click(function(){
        $(this).next().toggle();
    })
});

改变

 $(".test").click(function(){

To

 $(".test").live('click', function(){

现场演示

jQuery .live ()