Click an item with the same class.

I know this may sound silly, but for some reason I had some strange problem.

So, I have code in js that generates a table with buttons, which I gave to all the buttons of the same class.

when I try to click on them and use the jquery function for console.log nothing happens.

$.each(data,function(i, d){ $('#myTable tbody').append(` <tr> <td>${d.Date}</td> <td>${d.Name}</td> <td>${d.Score}</td> <td><button class='graphXY' data=${d.id}>View</button></td> </tr>`); }); 

its inside ajax and the table generates good, and each button gets a class and data.

now when i try to do

 $(".graphXY").click(function(){ console.log("hit"); }) 

in principle, nothing happens and for some reason I can not find the reason.

+5
source share
1 answer

The click() binding you use is called a "direct" binding, which only binds the handler to existing elements.

It will not be tied to elements created in the future. To do this, you need to create a "delegated" binding using on() .

 $("#myTable").on("click", ".graphXY", function(){ console.log("hit"); }) 
+2
source

Source: https://habr.com/ru/post/1275747/


All Articles