简体   繁体   English

通过php循环自动生成的jQuery ID选择器

[英]JQuery ID selector for auto generated through php loop

I'm new to JQuery, therefore I'm having difficulty catching element ID's that are generated automatically through my PHP loop. 我是JQuery的新手,因此很难捕获通过PHP循环自动生成的元素ID。

My question is how can I catch those automatically generated id's in JQuery, how to use loop in JQuery to catch a unique id, btw my id format is id="divAddressSet1", id="divAddressSet2" and so on. 我的问题是如何在JQuery中捕获那些自动生成的ID,如何在JQuery中使用循环捕获唯一ID,但我的ID格式是id="divAddressSet1", id="divAddressSet2" ,依此类推。 How I would be able to catch name(divAddressSet)+a unique number attached with each id in JQuery 我如何才能捕获name(divAddressSet)+a unique number jQuery中每个ID附加name(divAddressSet)+a unique number

Any idea? 任何想法?

Try to use attribute starts with selector at this context, 在这种情况下,尝试使用attribute starts with selector

$('[id^="divAddressSet"]')

Or do one thing, while generating those elements, just attach a common class to that. 或做一件事,在生成这些元素时,只需将一个通用类附加到该类。 And grab those elements with the help of class selector like, 并借助class selector抓取这些元素,例如

$('.commonClass')

Since your elements are created at runtime, use event-delegation as below, 由于您的元素是在运行时创建的,因此请按以下方式使用event-delegation

$(document).on("click" ,'.commonClass',function() {

});

And as a special note, replace, the closest static parent to .commonClass with document . 并特别说明一下,将最接近.commonClass静态父代替.commonClassdocument If you don't do that then the bound click event would get fired only after the propagation reaches to the document [$( document ).on(...)]. 如果您不这样做,则只有在propagation到达document [$( document ).on(...)]后,才会触发绑定的click事件。 Document is the root of the DOM, so it would cause performance lagging if you have a quite bigger dom structure.. 文档是DOM的根,因此,如果您具有较大的dom结构,则会导致性能下降。

use event delegation 使用event delegation

$(document).on("click" ,'[id^="divAddressSet"]',function() {

       alert(this.id);   
});

for id selector you use prefix " # " for class selector use " . " 对于id选择器,您使用前缀“ # ”作为类选择器使用“ .

Try this 尝试这个

Selectors Example : 选择器示例:

Starts with a given string (for example divAddressSet), 以给定的字符串开头(例如divAddressSet),

$("[id^='divAddressSet']")

If you want to select elements which id contains a given string : 如果要选择id包含给定字符串的元素:

$("[id*='divAddressSet']")

Script 脚本

$(document).on("click" ,'[id^="divAddressSet"]',function() {  });

OR 要么

$(document).on("click" ,'.yourclass',function() {  });

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

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