簡體   English   中英

如何對從Ajax動態添加的具有相同類的元素執行操作?

[英]How to apply an action on elements with the same class added dynamically from ajax?

我使用Ajax從數據庫獲取一些數據,從該Ajax請求返回的數據:

<p class="fetchedData">First Result</p>
<p class="fetchedData">Second Result</p>
<p class="fetchedData">Third Result</p>
<p class="fetchedData">Fourth Result</p>

單擊該如何獲取每個p元素內的文本?

就像單擊<p class="fetchedData">Fourth Result</p>我得到“第四結果”。

我試過了

var eachData $('.fetchedData').each(function(){
    $(this).on('click' , function(){
        console.log( $(this).text() );
    })
});

var allData = document.querySelectorAll('#fetchedData');
allData.forEach(function(el){
    console.log( $(this).text() );
}

但是他們都沒有工作。

我也嘗試過

$(document).on('click','.fetchedData' , function () {
    console.log( $(this).text() );
})

但這僅適用於第一個元素。

 $(document).ready(function() { $(document).on('click', '.fetchedData', function() { console.log($(this).text()); }) $.each(['First', 'Second', 'Third', 'Fourth'], function(index, value) { $('body').append(`<p class="fetchedData">${value} Result</p>`); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

您需要刪除var eachData並僅使用jQuery每個add click事件

$('.fetchedData').each(function(){
    $(this).on('click' , function(){
       console.log( $(this).text() );
    })
});

http://api.jquery.com/html/

使用.html()單擊上面的鏈接以供參考

否則使用document.getElementByClassName("className").value

如果每個數據都具有相同的類,則無需使用each循環。 您可以直接在.fetchedData類上應用click事件。

$('.fetchedData').on('click', function(){
    console.log($(this).text());
})

暫無
暫無

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

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