且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

新添加的div不会在文档就绪中继承事件处理程序

更新时间:2023-12-05 22:02:52

快捷方式事件处理程序(例如click()mouseover()等)将仅应用于页面加载时可用于DOM的元素.动态添加元素时,必须将事件附加到静态父元素,并提供希望将事件委托给的过滤器,如下所示:

The shortcut event handlers (such as click(), mouseover() etc) will only apply to elements which are available to the DOM on page load. When appending elements dynamically you have to attach the event to a static parent element, and supply a filter which you wish to delegate events to, like this:

$("body").on('mouseover', '.hoverme', function() {
    $(this).css({backgroundColor: '#000'});                    
});
$("body").on('mouseout', '.hoverme', function() {
    $(this).css({backgroundColor: '#0af'});                 
});

请注意,这里我已将body用作主要选择器.理想情况下,应该使用与.hoverme元素最接近的包含元素,该元素不会动态附加到DOM.

Note that I've used body here as the primary selector. Ideally you should use the closest containing element to the .hoverme elements which is not dynamically appended to the DOM.

工作小提琴

此外,您可以使用hover()稍微整理一下代码:

Also, you can slightly tidy your code by using hover():

$("body").on('hover', '.hoverme', function(e) {
    if (e.type === 'mouseenter')
        $(this).css({backgroundColor: '#000'}); 
    else
        $(this).css({backgroundColor: '#0af'});          
});

小提琴示例