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

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

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

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


当前回答

<html>
    <head>
        <title>HTML Document</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    </head>

    <body>
        <div id="hover-id">
            Hello World
        </div>

        <script>
            jQuery(document).ready(function($){
                $(document).on('mouseover', '#hover-id', function(){
                    $(this).css('color','yellowgreen');
                });

                $(document).on('mouseout', '#hover-id', function(){
                    $(this).css('color','black');
                });
            });
        </script>
    </body>
</html>

其他回答

jQuery.fn.on的文档中有一个很好的解释。

简而言之:

事件处理程序仅绑定到当前选定的元素;它们必须在代码调用.on()时存在于页面上。

因此,在下面的示例#dataTable中,生成代码之前必须存在tbodytr。

$("#dataTable tbody tr").on("click", function(event){
    console.log($(this).text());
});

如果新的HTML被注入到页面中,最好使用委托事件来附加事件处理程序,如下所述。

委派事件的优点是,它们可以处理来自后代元素的事件,这些后代元素稍后会添加到文档中。例如,如果表存在,但行是使用代码动态添加的,下面将处理它:

$("#dataTable tbody").on("click", "tr", function(event){
    console.log($(this).text());
});

除了处理尚未创建的后代元素上的事件的能力之外,委托事件的另一个优点是,当必须监视许多元素时,它们可以大大降低开销。在tbody中有1000行的数据表上,第一个代码示例将处理程序附加到1000个元素。

委托事件方法(第二个代码示例)只将事件处理程序附加到一个元素tbody,并且事件只需要向上冒泡一个级别(从单击的tr到tbody)。

注意:委派事件不适用于SVG。

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

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

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


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

另一种创建元素和绑定事件的灵活解决方案(源代码)

// creating a dynamic element (container div)
var $div = $("<div>", {id: 'myid1', class: 'myclass'});

//creating a dynamic button
 var $btn = $("<button>", { type: 'button', text: 'Click me', class: 'btn' });

// binding the event
 $btn.click(function () { //for mouseover--> $btn.on('mouseover', function () {
    console.log('clicked');
 });

// append dynamic button to the dynamic container
$div.append($btn);

// add the dynamically created element(s) to a static element
$("#box").append($div);

注意:这将为每个元素创建一个事件处理程序实例(在循环中使用时可能会影响性能)

这是通过事件委派完成的。事件将在包装器类元素上获得绑定,但将被委托给选择器类元素。这就是它的工作原理。

$('.wrapper-class').on("click", '.selector-class', function() {
    // Your code here
});

和HTML

<div class="wrapper-class">
    <button class="selector-class">
      Click Me!
    </button>
</div>    

#注:包装器类元素可以是任何东西,例如文档、主体或包装器。包装应该已经存在。然而,选择器不一定需要在页面加载时显示。它可能会在稍后出现,并且事件将毫无失败地绑定到选择器上。

创建对象时,可以将事件添加到对象中。如果您在不同的时间向多个对象添加相同的事件,那么创建命名函数可能是一种方法。

var mouseOverHandler = function() {
    // Do stuff
};
var mouseOutHandler = function () {
    // Do stuff
};

$(function() {
    // On the document load, apply to existing elements
    $('select').hover(mouseOverHandler, mouseOutHandler);
});

// This next part would be in the callback from your Ajax call
$("<select></select>")
    .append( /* Your <option>s */ )
    .hover(mouseOverHandler, mouseOutHandler)
    .appendTo( /* Wherever you need the select box */ )
;