我有一段代码,我循环浏览页面上的所有选择框,并将一个悬停事件绑定到它们上,以便在鼠标打开/关闭时对它们的宽度进行一些微调。

这在页面就绪时发生,工作正常。

我遇到的问题是,在初始循环之后通过Ajax或DOM添加的任何选择框都不会绑定事件。

我已经找到了这个插件(jQuery Live Query插件),但在我用插件向我的页面添加另一个5k之前,我想看看是否有人知道这样做的方法,无论是直接使用jQuery还是通过另一个选项。


当前回答

我更喜欢以模块化函数的方式部署事件侦听器,而不是编写文档级事件侦听器的脚本。所以,我喜欢下面。注意,您不能使用同一个事件侦听器超额订阅某个元素,因此不要担心多次附加侦听器-只需一个侦听器。

var迭代=4;var按钮;var body=document.querySelector(“body”);for(var i=0;i<迭代次数;i++){button=document.createElement(“button”);button.classList.add(“我的按钮”);button.appendChild(document.createTextNode(i));button.addEventListener(“单击”,myButtonWasClicked);body.appendChild(按钮);}函数myButtonWasClicked(e){console.log(e.target)//访问此特定按钮}

其他回答

你可以使用

$('.buttons').on('click', 'button', function(){
    // your magic goes here
});

or

$('.buttons').delegate('button', 'click', function() {
    // your magic goes here
});

这两种方法是等效的,但具有不同的参数顺序。

请参见:jQuery委托事件

您可以使用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>

另一种解决方案是在创建元素时添加侦听器。不是将监听器放在主体中,而是在创建元素的瞬间将监听器放入元素中:

var myElement = $('<button/>', {
    text: 'Go to Google!'
});

myElement.bind( 'click', goToGoogle);
myElement.append('body');


function goToGoogle(event){
    window.location.replace("http://www.google.com");
}

从jQuery 1.7开始,您应该使用jQuery.fn.on并填充选择器参数:

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

说明:

这称为事件委派,其工作方式如下。事件附加到应该处理的元素的静态父级(staticAncestors)。此jQuery处理程序在每次事件触发此元素或子元素之一时都会触发。然后,处理程序检查触发事件的元素是否与选择器(dynamicChild)匹配。如果匹配,则执行自定义处理程序函数。


在此之前,建议使用live():

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

然而,live()在1.7中被弃用,而在1.9中被完全删除。live()签名:

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

…可以替换为以下on()签名:

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

例如,如果您的页面正在动态创建类名为dosomething的元素,那么您可以将事件绑定到已经存在的父级(这是问题的症结所在,您需要绑定到现有的元素,而不是绑定到动态内容),这可以是文档(也是最简单的选项)。尽管记住文档可能不是最有效的选择。

$(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>

尝试使用.live()代替.bind();在Ajax请求执行后,.live()将把.holl绑定到您的复选框。