Jquery on event不绑定不存在的元素

Jquery on event is not binding for non existing elements

本文关键字:不存在 元素 绑定 on event Jquery      更新时间:2023-09-26

这里是jsfiddle的例子

http://jsfiddle.net/HTjCT/1/

你可以看到当你悬停的时候它不会触发mouseover事件

如何解决这个问题?

我使用Jquery 1.9

<div id='superdiv'>Click Me</div>

$(function () {
    $('#superdiv').on('click', function (event) {
        $('body').append('<div id="super">another');
    });
    $('#super').on('mouseover', function (event) {
        alert('not working');
    });
});
javascript

你必须使用"delegate",就像这样(提供"live")$('body').on('mouseover', '#super', function (event) {

您还可以将鼠标悬停事件包装在函数中,并在添加希望受影响的新元素时调用它。这样WickyNilliams指出的问题就不会影响到你了。

$(function () { 
    $('#superdiv').on('click', function (event) { 
        $('body').append('<div id="super">another');
        mouse();
    }); 
    function mouse () {
        $('#super').on('mouseover', function (event) { 
            alert('not working'); 
        }); 
    });
    mouse();
}

您想要创建onclick的div,没有使用'

' tag。

如果您尝试以下代码:

$(function () {
    $('#superdiv').on('click', function (event) {
        $('body').append(
            $('<div/>',{ 'id' : 'super', 'text' : 'tetet'}).mouseover(function(event) { 
                    alert('test'); 
            })
        );
    });
});