[英]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() );
})
});
使用.html()單擊上面的鏈接以供參考
否則使用document.getElementByClassName("className").value
如果每個數據都具有相同的類,則無需使用each循環。 您可以直接在.fetchedData類上應用click事件。
$('.fetchedData').on('click', function(){
console.log($(this).text());
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.