<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关联的单击事件。但是这个事件不起作用。

有人能帮忙吗?


当前回答

改变

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

To

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

现场演示

jQuery .live ()

其他回答

使用'on'作为点击绑定到已经存在的元素。

对如

$('test').on('click',function(){
    alert('Test');
})

这将有所帮助。

$(.surrounding_div_class).on( 'click', '.test', function () {
alert( 'WORKS!' );
});

只会工作,如果DIV类.surrounding_div_class是直接的父对象。test

如果在div中有另一个对象将被填充,它将不起作用。

我不能让live或委托在一个灯箱(小盒子)中的div上工作。

我成功地使用了setTimeout,以以下简单的方式:

$('#displayContact').click(function() {
    TINY.box.show({html:'<form><textarea id="contactText"></textarea><div id="contactSubmit">Submit</div></form>', close:true});
    setTimeout(setContactClick, 1000);
})

function setContactClick() {
    $('#contactSubmit').click(function() {
        alert($('#contactText').val());
    })
}

另一种更简洁的方法(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);

    });

使用委托对动态生成的内容应用事件的最佳方法。

$(document).on("eventname","selector",function(){
    // code goes here
});

你的代码现在是这样的

$(document).on("click",".test",function(){
    // code goes here
});