使用 AJAX 获取 html 内容后,向新元素添加侦听器的正确方法是什么?(jQuery,Javascript)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17821411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:45:22  来源:igfitidea点击:

What is a proper way to add listeners to new elements after using AJAX to get the html content? (jQuery, Javascript)

javascriptjqueryajaxaddeventlistener

提问by Lumin

I am making something that can loads new setting pages via AJAX, I am not sure what's the most efficient way to bind listeners to those elements from the new content page?

我正在制作一些可以通过 AJAX 加载新设置页面的东西,我不确定将侦听器绑定到新内容页面中的这些元素的最有效方法是什么?

Here's my thought. I can make a function that compares file path, and for each condition, then I will apply correct listeners to those new elements based on what page that AJAX loaded. I feel like it will makes the function so big if I have a large amount of pages.

这是我的想法。我可以创建一个比较文件路径的函数,并且对于每个条件,然后我将根据 AJAX 加载的页面对这些新元素应用正确的侦听器。我觉得如果我有大量的页面,它会使功能变得如此之大。

Thanks!

谢谢!

回答by Populus

Two ways:

两种方式:

1) Bind on a non-dynamic parent container using .on()

1) 使用绑定在非动态父容器上 .on()

$('.some-parent-class').on('click', '.element', function() {
  // DO STUFF!
});

2) Bind the new elements after ajax call is completed

2) ajax调用完成后绑定新元素

$.ajax(url, {
  // ajax options
}).done( function(data) {
  var newEl = $('<div class="element"></div>');
  // Setup your newEl with data here...
  newEl.on('click', function() {
    // do stuff
  });
  newEl.appendTo($('.some-parent-class'));
});

The former usually results in quicker ajax response times, but mayalso slow click responsiveness down.

前者通常会导致更快的 ajax 响应时间,但也可能会降低点击响应速度。

回答by Ohgodwhy

Use jQuery's .on()to handle event delegation. The first element you supply is a static element (never removed / replaced). the first argument is the event you wish to delegate against, mouseover/click, etc. The 2nd argument is the element we wish to have the event fire on when the event occurs. The 3rd argument is the callback, which is the function to run when the event fires.

使用 jQuery 的 . on()处理事件委托。您提供的第一个元素是静态元素(从未删除/替换)。第一个参数是您希望委托的事件,鼠标悬停/单击等。第二个参数是我们希望在事件发生时触发事件的元素。第三个参数是回调,它是事件触发时要运行的函数。

$(document).on('event', 'elementIdentifier', function(){
    //your code
});

回答by anyavacy

$(".parent-div").on("click", ".child-div-class-name" ,function(){
  somefunction();
});

all the new inserted elements inside the .parent-divwill be having the listeners onclick

里面所有新插入的元素.parent-div都会有听众onclick

回答by Kal

Adding on to Populus' answer, which is great as it is, a logically equivalent solution to his second option would be to use Promises:

再加上 Populus 的回答,尽管它很棒,但他的第二个选项的逻辑等效解决方案是使用Promises

     var iGotYou = new Promise(function (res, rej) {
        $.ajax({
             //ajax paramaters
        })
            .done(function( data ) {
                //handle the data as necessary...
                //then resolve the Promise
                res();
            });
    });

    //the Promise has been resolved
    iGotYou.then(function (response) {
        //add the event listener now that the promise has been fulfilled
       document.getElementById('someId').addEventListener('click', function (e) {
        //whatever you want to do on click event
       });
    })

回答by Jedediah

I'm not entirely sure what you're asking here, but you can use jQuery's .on() function to bind to elements that already exist in your document, OR elements that will exist in the future.

我不完全确定您在这里问的是什么,但是您可以使用 jQuery 的 .on() 函数绑定到文档中已经存在的元素,或者将来会存在的元素。

Here's a quick example:

这是一个快速示例:

$(document).ready(function () {
    $(document).on('click', '#new-button', function() {
        alert("You clicked the new button");
    });

    //get some HTML via ajax. Let's assume you're getting <button id="new-button">Click me</button>
    $.get('url', function(res) {
        $('body').append(res);
    });
});