I'm new to JQuery, therefore I'm having difficulty catching element ID's that are generated automatically through my PHP loop.
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. How I would be able to catch name(divAddressSet)+a unique number
attached with each id in JQuery
Any idea?
Try to use attribute starts with selector
at this context,
$('[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,
$('.commonClass')
Since your elements are created at runtime, use event-delegation
as below,
$(document).on("click" ,'.commonClass',function() {
});
And as a special note, replace, the closest static parent to .commonClass
with document
. If you don't do that then the bound click event would get fired only after the propagation
reaches to the document
[$( document ).on(...)]. Document is the root of the DOM, so it would cause performance lagging if you have a quite bigger dom structure..
use event delegation
$(document).on("click" ,'[id^="divAddressSet"]',function() {
alert(this.id);
});
for id selector you use prefix " #
" for class selector use " .
"
Try this
Selectors Example :
Starts with a given string (for example divAddressSet),
$("[id^='divAddressSet']")
If you want to select elements which id contains a given string :
$("[id*='divAddressSet']")
Script
$(document).on("click" ,'[id^="divAddressSet"]',function() { });
OR
$(document).on("click" ,'.yourclass',function() { });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.