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

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

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

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


当前回答

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

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

其他回答

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

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

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

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

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)//访问此特定按钮}

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

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

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