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

有人能帮忙吗?


当前回答

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

我在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()或.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/

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

对如

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

这将有所帮助。

改变

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

To

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

现场演示

jQuery .live ()