<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()时,使它为我工作的唯一方法是使用一个非动态的父作为:

<table id="myTable">
    <tr>
        <td></td> // Dynamically created
        <td></td> // Dynamically created
        <td></td> // Dynamically created
    </tr>
</table>

<input id="myButton" type="button" value="Push me!">

<script>
    $('#myButton').click(function() {
        $('#myTable tr').append('<td></td>');
    });

    $('#myTable').on('click', 'td', function() {
        // Your amazing code here!
    });
</script>

这非常有用,因为要删除与on()绑定的事件,可以使用off(),而要使用一次事件,可以使用one()。

其他回答

你需要使用.live来工作:

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

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

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

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

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

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

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

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

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

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

.live函数工作得很好。

它用于向舞台动态添加元素。

$('#selectAllAssetTypes').live('click', function(event){
                    alert("BUTTON CLICKED");
                    $('.assetTypeCheckBox').attr('checked', true);
                });

干杯, Ankit。

尝试.live()或.delegate()

http://api.jquery.com/live/

http://api.jquery.com/delegate/

您的.test元素被添加在.click()方法之后,因此它没有附加事件。Live和Delegate将事件触发器赋予检查子元素的父元素,因此之后添加的任何内容仍然有效。我认为Live将检查整个文档主体,而Delegate可以给一个元素,所以Delegate更有效。

更多信息:

http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/