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

有人能帮忙吗?


当前回答

我在jQuery的文档中找到了两个解决方案:

首先:在Body或Document上使用委托

例句:

 $("body").delegate('.test', 'click', function(){
 ...
  alert('test');
 });

Why?

答:根据一组特定的根元素,为现在或将来与选择器匹配的所有元素附加一个或多个事件处理程序。 链接:http://api.jquery.com/delegate/

第二步:将你的函数放在"$(document)"中,使用"on"并将它附加到你想要触发这个函数的元素上。 第一个参数是“事件处理器”,第二个参数是元素,第三个参数是函数。 例句:

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

Why?

Answer: Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next ... link: https://api.jquery.com/on/

其他回答

我不能让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());
    })
}

您遇到的问题是,您试图在DOM中有任何带有“test”类的东西之前将“test”类绑定到事件。虽然看起来这一切都是动态的,但真正发生的是JQuery传递DOM并在ready()函数触发时连接click事件,该事件发生在您在按钮事件中创建“click Me”之前。

通过将“test”Click事件添加到“button”单击处理程序,它将在DOM中存在正确的元素后将其连接起来。

<script type="text/javascript">
    $(document).ready(function(){                          
        $("button").click(function(){                                  
            $("h2").html("<p class='test'>click me</p>")                          
            $(".test").click(function(){                          
                alert()                          
            });       
        });                                     
    });
</script>

使用live()(正如其他人指出的那样)是另一种方法,但我觉得指出JS代码中的小错误也是一个好主意。你写的没有错,只是需要正确的范围。对于许多传统开发人员来说,掌握DOM和JS的工作原理是一件很棘手的事情。

Live()是一种更简洁的处理方法,在大多数情况下是正确的方法。它本质上是监视DOM,并在其中的元素发生变化时重新连接内容。

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

如果你有一个动态添加到某个容器或主体的链接:

var newLink= $("<a></a>", {
        "id": "approve-ctrl",
        "href": "#approve",
        "class": "status-ctrl",
        "data-attributes": "DATA"
    }).html("Its ok").appendTo(document.body);

你可以使用它的原始javascript元素并添加一个事件监听器,比如click:

newLink.get(0).addEventListener("click", doActionFunction);

无论你添加多少次这个新的链接实例,你都可以像使用jquery点击函数一样使用它。

function doActionFunction(e) {
    e.preventDefault();
    e.stopPropagation();

    alert($(this).html());
}

所以你会收到一条信息说

它的好

它比其他替代方案具有更好的性能。

额外:你可以获得更好的性能避免jquery和使用纯javascript。如果你使用的是ie8版本,你应该使用这个polyfill来使用addEventListener方法

if (typeof Element.prototype.addEventListener === 'undefined') {
    Element.prototype.addEventListener = function (e, callback) {
      e = 'on' + e;
      return this.attachEvent(e, callback);
    };
  }
$(.surrounding_div_class).on( 'click', '.test', function () {
alert( 'WORKS!' );
});

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

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