动态创建元素上的javascript事件绑定?

1yjd4xko  于 2021-08-25  发布在  Java
关注(0)|答案(23)|浏览(331)

这个问题的答案是社区的努力。编辑现有答案以改进此帖子。它目前不接受新的答案或互动。

我有一段代码,我在页面上的所有选择框中循环并绑定一个 .hover 事件,让他们在宽度上做一些旋转 mouse on/off .
这发生在PageReady上,效果很好。
我的问题是,在初始循环之后通过ajax或dom添加的任何选择框都不会绑定事件。
我找到了这个插件(jquerylivequeryplugin),但在我用插件向我的页面添加另一个5k之前,我想看看是否有人知道如何直接使用jquery或通过其他选项来实现这一点。

50pmv0ei

50pmv0ei1#

我正在寻找一个解决办法 $.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(){} );
e0bqpujr

e0bqpujr2#

<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>
csbfibhn

csbfibhn3#

从jQuery1.7开始,您应该使用 jQuery.fn.on 填充选择器参数后:

$(staticAncestors).on(eventName, dynamicChild, function() {});

说明:
这称为事件委派,其工作原理如下。事件被附加到静态父级( staticAncestors )应该处理的元素的。每次事件在此元素或一个子元素上触发时,都会触发此jquery处理程序。然后处理程序检查触发事件的元素是否与选择器匹配( dynamicChild ). 当存在匹配项时,将执行自定义处理程序函数。
在此之前,推荐的方法是使用 live() :

$(selector).live( eventName, function(){} );

然而, live() 在1.7中被弃用,取而代之的是 on() ,并在1.9中完全移除。这个 live() 签名:

$(selector).live( eventName, function(){} );

... 可替换为以下内容: on() 签名:

$(document).on( eventName, selector, function(){} );

例如,如果您的页面正在使用类名动态创建元素 dosomething 您可以将事件绑定到已存在的父级(这是问题的核心,您需要绑定到已存在的内容,而不是绑定到动态内容),这可以是(也是最简单的选项) document . 尽管记住 document 可能不是最有效的选择。

$(document).on('mouseover mouseout', '.dosomething', function(){
    // what you want to happen when mouseover and mouseout 
    // occurs on elements that match '.dosomething'
});

绑定事件时存在的任何父级都可以。例如

$('.buttons').on('click', 'button', function(){
    // do something here
});

适用于

<div class="buttons">
    <!-- <button>s that are generated dynamically and added here -->
</div>
vu8f3i0k

vu8f3i0k4#

在文档中有一个很好的解释 jQuery.fn.on .
简言之:
事件处理程序仅绑定到当前选定的元素;在代码调用时,它们必须存在于页面上 .on() .
因此,在下面的示例中 #dataTable tbody tr 必须在生成代码之前存在。

$("#dataTable tbody tr").on("click", function(event){
    console.log($(this).text());
});

如果将新的html注入页面,则最好使用委派事件来附加事件处理程序,如下所述。
委派事件的优点是,它们可以处理来自子元素的事件,这些子元素将在以后添加到文档中。例如,如果表存在,但行是使用代码动态添加的,则以下操作将对其进行处理:

$("#dataTable tbody").on("click", "tr", function(event){
    console.log($(this).text());
});

除了能够处理尚未创建的子元素上的事件外,委托事件的另一个优点是,当必须监视许多元素时,它们的开销可能会低得多。在数据表中包含1000行的 tbody ,第一个代码示例将处理程序附加到1000个元素。
委派事件方法(第二个代码示例)只将事件处理程序附加到一个元素,即 tbody ,事件只需向上冒泡一个级别(从单击的 trtbody ).
注意:委派事件不适用于svg。

vybvopom

vybvopom5#

这是一个没有任何库或插件的纯javascript解决方案:

document.addEventListener('click', function (e) {
    if (hasClass(e.target, 'bu')) {
        // .bu clicked
        // Do your thing
    } else if (hasClass(e.target, 'test')) {
        // .test clicked
        // Do your other thing
    }
}, false);

哪里 hasClass

function hasClass(elem, className) {
    return elem.className.split(' ').indexOf(className) > -1;
}

现场演示
这归功于戴夫和西姆·维达斯
使用更现代的js, hasClass 可实施为:

function hasClass(elem, className) {
    return elem.classList.contains(className);
}
ki0zmccv

ki0zmccv6#

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

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

6pp0gazn7#

您可以简单地将事件绑定调用 Package 到一个函数中,然后调用它两次:一次在文档就绪时调用,一次在添加新dom元素的事件之后调用。如果这样做,您将希望避免在现有元素上绑定同一事件两次,因此您需要解除现有事件的绑定,或者(更好)只绑定到新创建的dom元素。代码如下所示:

function addCallbacks(eles){
    eles.hover(function(){alert("gotcha!")});
}

$(document).ready(function(){
    addCallbacks($(".myEles"))
});

// ... add elements ...
addCallbacks($(".myNewElements"))
gdrx4gfi

gdrx4gfi8#

尝试使用 .live() 而不是 .bind() ; 这个 .live() 将绑定 .hover 在ajax请求执行后,单击复选框。

bxfogqkk

bxfogqkk9#

动态创建元素上的事件绑定

单一元素:

$(document.body).on('click','.element', function(e) {  });

子元素:

$(document.body).on('click','.element *', function(e) {  });

注意添加的 * . 将为该元素的所有子元素触发一个事件。
我注意到:

$(document.body).on('click','.#element_id > element', function(e) {  });

它不再起作用了,但它以前起过作用。我一直在使用谷歌cdn的jquery,但我不知道他们是否改变了它。

7kqas0il

7kqas0il10#

我更喜欢使用选择器,并将其应用于文档。
这将在文档上绑定自身,并将适用于页面加载后呈现的元素。
例如:

$(document).on("click", 'selector', function() {
    // Your code here
});
ttvkxqim

ttvkxqim11#

可以使用live()方法将元素(甚至是新创建的元素)绑定到事件和处理程序,如onclick事件。
下面是我编写的示例代码,您可以看到live()方法如何将所选元素(甚至是新创建的元素)绑定到事件:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
    </head>

    <body>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js"></script>

        <input type="button" id="theButton" value="Click" />
        <script type="text/javascript">
            $(document).ready(function()
                {
                    $('.FOO').live("click", function (){alert("It Works!")});
                    var $dialog = $('<div></div>').html('<div id="container"><input type ="button" id="CUSTOM" value="click"/>This dialog will show every time!</div>').dialog({
                                                                                                         autoOpen: false,
                                                                                                         tite: 'Basic Dialog'
                                                                                                     });
                    $('#theButton').click(function()
                    {
                        $dialog.dialog('open');
                        return('false');
                    });
                    $('#CUSTOM').click(function(){
                        //$('#container').append('<input type="button" value="clickmee" class="FOO" /></br>');
                        var button = document.createElement("input");
                        button.setAttribute('class','FOO');
                        button.setAttribute('type','button');
                        button.setAttribute('value','CLICKMEE');
                        $('#container').append(button);
                    });
                    /* $('#FOO').click(function(){
                                                     alert("It Works!");
                                                 }); */
            });
        </script>
    </body>
</html>
7y4bm7vi

7y4bm7vi12#

这是由事件委派完成的。事件将在 Package 类元素上获得绑定,但将委托给选择器类元素。这就是它的工作原理。

$('.wrapper-class').on("click", '.selector-class', function() {
    // Your code here
});

和html

<div class="wrapper-class">
    <button class="selector-class">
      Click Me!
    </button>
</div>

注意: Package 器类元素可以是任何东西,例如文档、主体或 Package 器。 Package 器应该已经存在。然而, selector 不一定需要在页面加载时显示。它可能会晚一点到来,事件将继续进行 selector 毫无疑问。

vohkndzv

vohkndzv13#

另一个解决方案是在创建元素时添加侦听器。在创建元素时,您将侦听器放入元素中,而不是将其放入主体中:

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

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

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

ujv3wf0j14#

试着这样做-

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

kiz8lqtg15#

注意放置元素的“main”类,例如,

<div class="container">
     <ul class="select">
         <li> First</li>
         <li>Second</li>
    </ul>
</div>

在上述场景中,jquery将监视的主要对象是“container”。
然后,基本上在容器下有元素名称,例如 ul , li ,及 select :

$(document).ready(function(e) {
    $('.container').on( 'click',".select", function(e) {
        alert("CLICKED");
    });
 });

相关问题