【问题标题】:Jquery on event is not binding for non existing elementsJquery on event 不绑定不存在的元素
【发布时间】:2013-01-18 14:23:32
【问题描述】:

好的,这里是 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

【问题讨论】:

    标签: javascript jquery event-delegation


    【解决方案1】:

    你必须使用“代表”,像这样(提供“现场”) $('body').on('mouseover', '#super', function (event) {

    【讨论】:

    • 虽然这是正确的,但请不要开始将所有事件处理程序附加到正文。事件委托的工作原理是捕获 每个 冒泡的事件,然后检查源元素以查看它是否与感兴趣的元素匹配(此处为#super)。因此,每次您将鼠标悬停在页面上的 anything 上时,您都会遇到检查该元素是否匹配的问题。让你的 delegate 尽量本地化到源头,你会得到更好的表现,而不是每次都粘在 body 上
    • 这是绝对正确的,只是为了这个例子显示委托。
    【解决方案2】:

    您还可以将鼠标悬停事件包装在一个函数中,并在您添加想要影响的新元素时调用它。 这样,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();
    }
    

    【讨论】:

      【解决方案3】:

      你要onclick创建的div,不是用'

      '标签封闭的。

      如果您尝试以下代码会怎样:

      $(function () {
          $('#superdiv').on('click', function (event) {
              $('body').append(
                  $('<div/>',{ 'id' : 'super', 'text' : 'tetet'}).mouseover(function(event) { 
                          alert('test'); 
                  })
              );
          });
      });
      
      猜你喜欢
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-19
      相关资源
      最近更新 更多