简体   繁体   English

动态生成id时获取链接的id

[英]Get id of link when id is dynamically generated

I have a div with a bunch of stuff in it. 我的div中有一堆东西。 I also have a link inside that div, which has a dynamically generated id. 我在该div中也有一个链接,该链接具有动态生成的ID。 There's no way to tell what the id will be. 无法告诉您ID是什么。

When I click that link, how can I get the id of that link into a variable jQuery? 当我单击该链接时,如何将该链接的ID转换为变量jQuery? In a *.js file? 在* .js文件中?

Try this, 尝试这个,

With Tag Name 带标签名称

$('a').click(function(){
 //alert($(this).attr('id');  
 alert(this.id); //Better then the statement above as it is javascript with jQuery wrapper
});

With class 带班

$('.classOfAnchor').click(function(){
 alert($(this).attr('id');
 alert(this.id);  //Better then the statement above as it is javascript with jQuery wrapper
});
$("a").click(function() {
    //alert( $(this).attr('id') );
     alert(this.id); //Better then above
});

Unless something gives the element an id, there won't be one. 除非某物为元素提供了ID,否则就不会有ID。

But, for the sake of explanation, lets say there definitely is an ID on that link.. 但是,为了便于说明,可以说该链接上肯定有一个ID。

if you were using jQuery, you could simply select its container div and then traverse down to the link: var myID = $('div#theContainingDiv').children('a').attr('id'); 如果您使用的是jQuery,则只需选择其容器div,然后向下浏览至链接: var myID = $('div#theContainingDiv').children('a').attr('id');

or, you can just do what the other people said to do -- that will work too. 或者,您也可以按照别人说的去做-也可以。

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

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