143

我想将 onclick 事件绑定到我用 jQuery 动态插入的元素

但它从不运行绑定的函数。如果您能指出为什么这个例子不起作用以及如何让它正常运行,我会很高兴:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"        
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="da" lang="da">
        <head>
          <title>test of click binding</title>

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
          <script type="text/javascript">


        jQuery(function(){
          close_link = $('<a class="" href="#">Click here to see an alert</a>');
          close_link.bind("click", function(){
            alert('hello from binded function call');
            //do stuff here...
          });
  
          $('.add_to_this').append(close_link);
        });
          </script>
        </head>
        <body>
          <h1 >Test of click binding</h1>
          <p>problem: to bind a click event to an element I append via JQuery.</p>

          <div class="add_to_this">
            <p>The link is created, then added here below:</p>
          </div>

          <div class="add_to_this">
            <p>Another is added here below:</p>
          </div>


        </body>
        </html>

编辑:我编辑了示例以包含该方法插入到的两个元素。在这种情况下,alert()调用永远不会被执行。(感谢@Daff 在评论中指出这一点)

4

9 回答 9

328

所有这些方法都已弃用。您应该使用该on方法来解决您的问题。

如果要定位动态添加的元素,则必须使用

$(document).on('click', selector-to-your-element , function() {
     //code here ....
});

这替换了不推荐使用的.live()方法。

于 2012-10-01T13:03:14.937 回答
71

第一个问题是,当您在具有多个元素的 jQuery 集合上调用 append 时,会为每个元素创建要附加的元素的克隆,因此会丢失附加的事件观察器。

另一种方法是为每个元素创建链接:

function handler() { alert('hello'); }
$('.add_to_this').append(function() {
  return $('<a>Click here</a>').click(handler);
})

另一个潜在的问题可能是在元素被添加到 DOM 之前附加了事件观察器。我不确定这是否有什么要说的,但我认为这种行为可能被认为是不确定的。更可靠的方法可能是:

function handler() { alert('hello'); }
$('.add_to_this').each(function() {
  var link = $('<a>Click here</a>');
  $(this).append(link);
  link.click(handler);
});
于 2009-10-07T08:33:53.400 回答
51

Live方法怎么样?

$('.add_to_this a').live('click', function() {
    alert('hello from binded function call');
});

不过,你所做的看起来应该可以工作。还有一个帖子看起来很相似。

于 2009-10-06T13:53:07.463 回答
23

聚会有点晚了,但我想我会尝试澄清一些在 jQuery 事件处理程序中常见的误解。从 jQuery 1.7 开始,.on()应该使用而不是 deprecated.live()来将事件处理程序委托给在分配事件处理程序后的任何时候动态创建的元素。

也就是说,这不是简单的切换liveon因为语法略有不同:

新方法(示例 1):

$(document).on('click', '#someting', function(){

});

不推荐使用的方法(示例 2):

$('#something').live(function(){

});

如上图,有区别。通过将选择器传递给 jQuery 函数本身,扭曲.on()实际上可以类似于 调用.live()

示例 3:

$('#something').on('click', function(){

});

但是,如果不使用$(document)示例 1,示例 3 将不适用于动态创建的元素。如果您不需要动态委托,示例 3 绝对可以。

$(document).on() 应该用于所有内容吗?

它会起作用,但如果您不需要动态委派,则使用示例 3 会更合适,因为示例 1 需要浏览器做更多的工作。不会对性能产生任何实际影响,但使用最适合您的方法是有意义的。

如果不需要动态委托,是否应该使用 .on() 而不是 .click()?

不必要。以下只是示例 3 的快捷方式:

$('#something').click(function(){

});

以上是完全有效的,因此在不需要动态委托时使用哪种方法实际上是个人喜好问题。

参考:

于 2013-06-13T11:48:33.570 回答
2

考虑一下:

jQuery(function(){
  var close_link = $('<a class="" href="#">Click here to see an alert</a>');
      $('.add_to_this').append(close_link);
      $('.add_to_this').children().each(function()
      {
        $(this).click(function() {
            alert('hello from binded function call');
            //do stuff here...
        });
      });
});

它会起作用,因为您将它附加到每个特定元素。这就是为什么您需要 - 在将链接添加到 DOM 之后 - 找到一种方法来显式选择您添加的元素作为 DOM 中的 JQuery 元素并将点击事件绑定到它。

最好的方法可能是 - 正如建议的那样 - 通过 live 方法将其绑定到特定类。

于 2009-10-06T13:43:19.930 回答
2

与元素一起创建单击事件是可能的,有时是必要的。例如,当基于选择器的绑定不是一个选项时。关键部分是通过在单个元素上使用来避免Tobias所说的问题。.replaceWith()请注意,这只是一个概念证明。

<script>
    // This simulates the object to handle
    var staticObj = [
        { ID: '1', Name: 'Foo' },
        { ID: '2', Name: 'Foo' },
        { ID: '3', Name: 'Foo' }
    ];
    staticObj[1].children = [
        { ID: 'a', Name: 'Bar' },
        { ID: 'b', Name: 'Bar' },
        { ID: 'c', Name: 'Bar' }
    ];
    staticObj[1].children[1].children = [
        { ID: 'x', Name: 'Baz' },
        { ID: 'y', Name: 'Baz' }
    ];

    // This is the object-to-html-element function handler with recursion
    var handleItem = function( item ) {
        var ul, li = $("<li>" + item.ID + " " + item.Name + "</li>");

        if(typeof item.children !== 'undefined') {
            ul = $("<ul />");
            for (var i = 0; i < item.children.length; i++) {
                ul.append(handleItem(item.children[i]));
            }
            li.append(ul);
        }

        // This click handler actually does work
        li.click(function(e) {
            alert(item.Name);
            e.stopPropagation();
        });
        return li;
    };

    // Wait for the dom instead of an ajax call or whatever
    $(function() {
        var ul = $("<ul />");

        for (var i = 0; i < staticObj.length; i++) {
            ul.append(handleItem(staticObj[i]));
        }

        // Here; this works.
        $('#something').replaceWith(ul);
    });
</script>
<div id="something">Magical ponies ♥&lt;/div>
于 2013-07-09T08:13:26.780 回答
1
    function load_tpl(selected=""){
        $("#load_tpl").empty();
        for(x in ds_tpl){
            $("#load_tpl").append('<li><a id="'+ds_tpl[x]+'" href="#" >'+ds_tpl[x]+'</a></li>');
        }
        $.each($("#load_tpl a"),function(){
            $(this).on("click",function(e){
                alert(e.target.id);
            });
        });
    }
于 2017-06-06T00:19:40.837 回答
0

我相信这样做的好方法:

$('#id').append('<a id="#subid" href="#">...</a>');
$('#subid').click( close_link );
于 2009-10-06T13:47:12.297 回答
-1
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>    
<script>
    $(document).ready(function(){
        $(document).on('click', '.close', function(){
            var rowid='row'+this.id;
            var sl = '#tblData tr[id='+rowid+']';
            console.log(sl);
            $(sl).remove();
        });
        $("#addrow").click(function(){
            var row='';
            for(var i=0;i<10;i++){
                row=i;
                row='<tr id=row'+i+'>'
                    +   '<td>'+i+'</td>'
                    +   '<td>ID'+i+'</td>'
                    +   '<td>NAME'+i+'</td>'
                    +   '<td><input class=close type=button id='+i+' value=X></td>'
                    +'</tr>';
                console.log(row);
                $('#tblData tr:last').after(row);
            }
        });
    });

</script>
</head>
  <body>
    <br/><input type="button" id="addrow" value="Create Table"/>
    <table id="tblData" border="1" width="40%">
        <thead>
        <tr>
            <th>Sr</th>
            <th>ID</th>
            <th>Name</th>
            <th>Delete</th>
        </tr>
        </thead>
    </table>
    </body>
 </html>
于 2017-05-14T04:43:00.880 回答