javascript如何为创建的元素(DOM节点)动态绑定事件

时间:2017-07-28
项目开发中经常需要为动态创建的节点绑定事件,比如需要创建一个动态li列表并且为这些动态li列表绑定事件,这时用javascrit如何实现呢?大家仔细看完这篇文章就知道如何为创建的元素动态绑定事件了。

您可以使用live()方法将元素(甚至新创建的元素)绑定到事件和处理程序,如onclick事件。

以下是我编写的示例代码,您可以在其中看到live()方法如何将所选元素(甚至新创建的元素)绑定到事件中:

<!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">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
    </head>

    <body>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js"></script>

        <input type="button" id="theButton" value="Click" />
        <script type="text/javascript">
            $(document).ready(function()
                {
                    $('.FOO').live("click", function (){alert("It Works!")});
                    var $dialog = $('<div></div>').html('<div id="container"><input type ="button" id="CUSTOM" value="click"/>This dialog will show every time!</div>').dialog({
                                                                                                         autoOpen: false,
                                                                                                         tite: 'Basic Dialog'
                                                                                                     });
                    $('#theButton').click(function()
                    {
                        $dialog.dialog('open');
                        return('false');
                    });
                    $('#CUSTOM').click(function(){
                        //$('#container').append('<input type="button" value="clickmee" class="FOO" /></br>');
                        var button = document.createElement("input");
                        button.setAttribute('class','FOO');
                        button.setAttribute('type','button');
                        button.setAttribute('value','CLICKMEE');
                        $('#container').append(button);
                    });
                    /* $('#FOO').click(function(){
                                                     alert("It Works!");
                                                 }); */
            });
        </script>
    </body>
</html>

从jQuery 1.7开始你应该使用jQuery.fn.on

$(staticAncestors).on(eventName, dynamicChild, function() {});

在此之前,推荐的方法是使用live()

$(selector).live( eventName, function(){} );

但是,live()在1.7中被弃用on(),并在1.9中完全删除。该live()签名:

$(selector).live( eventName, function(){} );

也可以用以下on()替换:

$(document).on( eventName, selector, function(){} );

例如,如果您的页面动态创建具有类名称dosomething的元素,那么您将事件绑定到已存在的父项document

$(document).on('mouseover mouseout', '.dosomething', function(){
    // what you want to happen when mouseover and mouseout 
    // occurs on elements that match '.dosomething'
});

将事件绑定到任何存在的父级元素都是可以的。例如

$('.buttons').on('click', 'button', function(){
    // do something here
});

将适用于

<div class="buttons">
    <!-- <button>s that are generated dynamically and added here -->
</div>