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

mzmfm0qo  于 10个月前  发布在  jQuery
关注(0)|答案(5)|浏览(88)

我做的东西,可以通过AJAX加载新的设置页面,我不知道什么是最有效的方式绑定侦听器到这些元素从新的内容页面?
这里是我的想法.我可以做一个函数,比较文件路径,并为每一个条件,然后我会应用正确的侦听器,这些新元素的基础上,什么网页,AJAX加载.我觉得这将使函数如此之大,如果我有大量的网页.
谢谢你,谢谢

yyyllmsg

yyyllmsg1#

两种方式:
1)使用.on()绑定到非动态父容器

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

字符串
2)在一次调用完成后绑定新元素

$.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'));
});


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

liwlm1x9

liwlm1x92#

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

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

字符串

w46czmvw

w46czmvw3#

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

字符串
.parent-div中插入的所有新元素都将拥有监听器onclick

7ivaypg9

7ivaypg94#

再加上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
       });
    })

字符串

nzk0hqpo

nzk0hqpo5#

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

$(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);
    });
});

字符串

相关问题