簡體   English   中英

在使用AJAX獲取html內容后,將偵聽器添加到新元素的正確方法是什么? (jQuery,Javascript)

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

我正在制作可以通過AJAX加載新設置頁面的東西,我不確定將偵聽器綁定到新內容頁面中的那些元素的最有效方法是什么?

這是我的想法。 我可以創建一個比較文件路徑的函數,對於每個條件,然后我將根據AJAX加載的頁面將正確的偵聽器應用於這些新元素。 如果我有大量的頁面,我覺得它會使功能如此之大。

謝謝!

兩種方式:

1)使用.on()綁定非動態父容器

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

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

前者通常會導致更快的ajax響應時間,但也可能會降低點擊響應速度。

使用jQuery。 on()處理事件委托。 您提供的第一個元素是靜態元素(從不刪除/替換)。 第一個參數是您希望委托的事件,鼠標懸停/單擊等。第二個參數是我們希望事件發生時觸發事件的元素。 第三個參數是回調,它是事件觸發時運行的函數。

$(document).on('event', 'elementIdentifier', function(){
    //your code
});
$(".parent-div").on("click", ".child-div-class-name" ,function(){
  somefunction();
});

.parent-div所有新插入元素都將具有偵聽器onclick

除了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
       });
    })

我不完全確定你在這里問的是什么,但你可以使用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);
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM