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

有人能帮忙吗?


当前回答

你需要使用.live来工作:

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

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

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

其他回答

在js文件中添加这个函数。 它可以在所有浏览器上运行

$(函数(){ 美元(文档)。On ("click", '#mydiv', function() { 提示(“您刚刚点击了”); }); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> < div id =“mydiv”> div < / div >

我正在使用表动态地添加新元素,当使用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()。

你也可以使用onclick="do_something(this) "“内部元素

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

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

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

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

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

你的代码现在是这样的

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