简体   繁体   中英

How jquery get dynamic element id

I have jsp element id that is dynamically setup.
It looks like id=<%= config.getName()%>
How can I get the id of those when I click them?

How to pass the element id to the function like:

$('****').click(function(){

}

Add c class name on your button.

<input type='button' class='myButtonClass' id=<%= config.getName()%> />

You can now use the class as selector.. You have, i guess 3 ways to get the id attribute.

$('.myButtonClass').click(function(){
    // first option
    console.log(this.id); // use this only, not $(this), .id will not work on jquery object
   // second option
   console.log($(this).prop('id'));
   // third option 
   console.log($(this).attr('id'));

});

you can use class to get dynamic id as:

$(".any").click(function(){
alert($(this).attr("id"));
});

Isn't there another unique attribute? for example, class name, tag name,...

if nothing, there is another way that create unique attribute value in the tag.

<div id=<%=config.getName()%> dynamicId="true"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script>
$(document).ready(function()
{
$(".common").click(function()
{
alert(this.className);
alert(this.id);
//  here u can get class name id  value and pass to any function u want 
// functinname(this.className);
});

});
</script>


<div id="vik" class="common">vik div</div>
<div id="cha" class="common">cha div</div>

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.

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