简体   繁体   English

jQuery如何获取动态元素ID

[英]How jquery get dynamic element id

I have jsp element id that is dynamically setup. 我有可以动态设置的jsp元素ID。
It looks like id=<%= config.getName()%> 看起来像是id=<%= config.getName()%>
How can I get the id of those when I click them? 单击它们时,如何获取这些ID?

How to pass the element id to the function like: 如何将元素id传递给函数,例如:

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

}

Add c class name on your button. 在按钮上添加c类名称。

<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. 您现在可以使用该类作为选择器。.我想您可以通过3种方法来获取id属性。

$('.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: 您可以使用class获取动态ID,如下所示:

$(".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>

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

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