Javascript 使用javascript获取div id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7071748/
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 div id using javascript
提问by ingh.am
Here's some HTML:
这是一些HTML:
<div class="results">
<div id="1">something</div>
<div id="2">something else</div>
<div id="3">blah blah blah</div>
<div id="4">etc</div>
</div>
Now if I can call this using jQuery:
现在,如果我可以使用 jQuery 调用它:
var div = $(".results > div");
div.click(function()
{
alert(this.childNodes[0].nodeValue);
});
When clicking on a div, it will call an alert box saying whats in the div (from the list above: one of 'something', 'something else', 'blah blah blah' or 'etc'). Does anyone know how I can get it to alert the id (in this example, 1, 2, 3 or 4) of the div rather than the information within the node?
单击 div 时,它会调用一个警告框,说明 div 中的内容(来自上面的列表:“某物”、“其他东西”、“等等”或“等等”之一)。有谁知道我如何让它提醒 div 的 id(在本例中为 1、2、3 或 4)而不是节点内的信息?
Thanks
谢谢
回答by Felix Kling
Inside the event handler, this
refers to the clicked div
. You can access its id
property [MDN]:
在事件处理程序中,this
指的是 clicked div
。您可以访问其id
属性[MDN]:
alert(this.id);
Note:HTML4 does not allow id
s to start with digits.
注意:HTML4 不允许id
s 以数字开头。
P.S: The selector should be (fixed)$(".results > div")
.
PS:选择器应该是(固定的)$(".results > div")
.
回答by Paul
Alert the id property of the div:
提醒 div 的 id 属性:
alert(this.id);