javascript 获取点击链接的 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12441485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get ID of a Clicked Link
提问by JasonDavis
In the code below and demo here http://jsfiddle.net/jasondavis/vp2YN/3/you can see I need to get the ID attribute of a clicked item and assign it to a variable in Javascript.
在下面的代码和演示http://jsfiddle.net/jasondavis/vp2YN/3/ 中,您可以看到我需要获取单击项目的 ID 属性并将其分配给 Javascript 中的变量。
Right now the code returns the ID name of the first item, regardless of which item is clicked on.
现在,无论单击哪个项目,代码都会返回第一个项目的 ID 名称。
In the Javascript you can see I have this line commented out...
在 Javascript 中,您可以看到我将这一行注释掉了...
var clickedID = this.attr("id");
when I use that line, I get an error saying: Object has no method 'attr'
var clickedID = this.attr("id");
当我使用那条线时,我收到一条错误消息: Object has no method 'attr'
Please help me get the ID name of the clicked link and assign it to a variable
请帮我获取点击链接的 ID 名称并将其分配给一个变量
HTML
HTML
<a href="#" style="display:block" class="button insertcolumn" id="one_half">2 Columns</a>
<a href="#" style="display:block" class="button insertcolumn" id="one_third">3 Columns</a>
<a href="#" style="display:block" class="button insertcolumn" id="one_fourth">4 Columns</a>?
Javascript/jQuery
Javascript/jQuery
jQuery('.insertcolumn').click(function(){
var clickedID = jQuery('.insertcolumn').attr("id");
//var clickedID = this.attr("id");
alert(clickedID);
});?
回答by Zevi Sternlicht
You have to reference the one you clicked with the jQuery wrapper!
您必须引用您使用 jQuery 包装器单击的那个!
You want to use
你想用
$(this).attr('id');
To get the id (without traversing the DOM for no reason) you would be better off to just call the object id
.
要获取 id (无需无缘无故地遍历 DOM),您最好只调用 object id
。
this.id;
But to access the property regardless of the type of attribute and depending on the name of the attribute use the following code.
但是无论属性的类型如何并根据属性的名称访问该属性,请使用以下代码。
jQuery('.insertcolumn').click(function(){
var clickedID = $(this).attr('id');
alert(clickedID);
});?