Jquery从动态元素获取id或类

假设我有来自PHP查询的 5个元素(所以它是动态的)如下图所示:

element 1 class=element id=id_1 element 2 class=element id=id_2 element 3 class=element id=id_3 element 4 class=element id=id_4 element 5 class=element id=id_5 

我们通过了解他们的id来使用jquery事件 ,但在这种情况下,我们并不完全知道他们的id

 $("#id_3").click(function() { //in this case we have known we want to add event when we click id_3 }); 

如何处理PHP查询中的动态元素?
例如,我们怎么知道我们用id_3点击element 3
我们必须填写$(????).click();
当我使用class时,如何知道我从类中引用了哪个id

在您的示例中,元素都具有相同的类,因此您可以基于此设置事件处理程序:

 $(".element").click(function() { // "this" refers to the clicked element // this.id will be the id of the clicked element }); 

或者,如果这些元素在初始页面加载后的某个时刻通过Ajax加载的意义上是动态的,则使用委托的事件处理程序:

 $("somecontainerelement").on("click", ".element", function() { // do something with this.id }); 

其中“somecontainerelement”理想情况下是动态元素添加到的元素,但可能只是document

这是我能让它发挥作用的唯一方法。 例如,如果您想获取属性ID或已单击的元素的值…

 $("containerElem").on("click", "someElemID", function(evt) { var getElemID = $(evt.target).attr("id"); var getVal = $(evt.target).val(); }); 

如果它们都具有相同的类,则可以使用类选择器。 然后使用this来查找您所追求的任何属性。

 $('.element').click( $(this).prop('id'); ); 

如果您只想添加点击,那么为什么不将它添加到服务器端生成的html?

您可以使用attribute starsWith selector& on来绑定动态创建的元素on事件。

 $('body').on('click', '[id^=id]', function(e){ }); 

当我们使用id或class处理未知元素时,这非常有用

 $( document ).ready(function() { // user this if element is div $('div[id^="id_"]').on('click', function() { alert($(this).attr('id')); }); // user this if element is input $('input[id^="id_"]').on('click', function() { alert(this.id); }); });