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

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

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

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


当前回答

这样试试-

$(document).on( 'click', '.click-activity', function () { ... });

其他回答

动态创建的元素上的事件绑定

单个元素:

$(document.body).on('click','.element', function(e) {  });

子元素:

 $(document.body).on('click','.element *', function(e) {  });

注意添加的*。将为该元素的所有子级触发事件。

我注意到:

$(document.body).on('click','.#element_id > element', function(e) {  });

它已经不起作用了,但它以前也起过作用。我一直在使用谷歌CDN的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>

我正在寻找一种解决方案,使$.bind和$.unbind在动态添加的元素中工作时不会出现问题。

As on()使用了附加事件的技巧,以便在我遇到的事件上创建一个假解绑:

const sendAction = function(e){ ... }
// bind the click
$('body').on('click', 'button.send', sendAction );

// unbind the click
$('body').on('click', 'button.send', function(){} );

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

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 */ )
;

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

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

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


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