简体   繁体   English

如何对从Ajax动态添加的具有相同类的元素执行操作?

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

I use Ajax to get some data from a Database , The returned data from that Ajax request : 我使用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>

How can I get the text inside each p element on clicking it? 单击该如何获取每个p元素内的文本?

Like when clicking on the <p class="fetchedData">Fourth Result</p> I get "Fourth Result". 就像单击<p class="fetchedData">Fourth Result</p>我得到“第四结果”。

I tried 我试过了

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

And

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

But none of them worked . 但是他们都没有工作。

Also I tried 我也尝试过

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

But it just works on the first element. 但这仅适用于第一个元素。

 $(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> 

You need remove var eachData and just use jQuery each add click event 您需要删除var eachData并仅使用jQuery每个add click事件

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

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

use .html() click the above link for reference 使用.html()单击上面的链接以供参考

or else use document.getElementByClassName("className").value 否则使用document.getElementByClassName("className").value

No need to use an each loop if you have same class for every data. 如果每个数据都具有相同的类,则无需使用each循环。 You can directly apply on click event over .fetchedData class. 您可以直接在.fetchedData类上应用click事件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM