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

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

我遇到的问题是,在初始循环之后通过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 */ )
;

其他回答

当使用jQuery(html,属性)动态创建时,可以将事件附加到元素。

从jQuery1.8开始,任何jQuery实例方法(jQuery.fn的方法)都可以用作传递给第二个参数:

函数handleDynamicElementEvent(事件){console.log(事件类型,此值)}//创建事件并将其附加到动态元素jQuery(“<select>”{html:$.map(数组(3),函数(_,索引){返回新选项(索引,索引)}),日期:{更改:handleDynamicElementEvent}}).appendTo(“正文”);<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

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

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


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

我正在寻找一种解决方案,使$.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(){} );

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

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

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

这样试试-

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