<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()。

其他回答

改变

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

To

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

现场演示

jQuery .live ()

Jquery .on的工作可以,但我有一些问题的渲染实现上面的一些解决方案。我使用.on的问题是,它在某种程度上呈现的事件不同于.hover方法。

只是供其他可能也有这个问题的人参考。我通过为动态添加的项目重新注册悬浮事件来解决我的问题:

重新注册悬停事件,因为悬停对动态创建的项目不起作用。 所以每次我创建新的/动态项目时,我都会再次添加悬停代码。完美的作品

$('#someID div:last').hover(
    function() {
       //...
    },
    function() {
       //...
    }
);

尝试.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/

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

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

    });