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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:43:48  来源:igfitidea点击:

Get div id using javascript

javascriptjquery

提问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, thisrefers to the clicked div. You can access its idproperty [MDN]:

在事件处理程序中,this指的是 clicked div。您可以访问其id属性[MDN]

alert(this.id);

Note:HTML4 does not allow ids to start with digits.

注意:HTML4 不允许ids 以数字开头。

P.S: The selector should be $(".results > div").(fixed)

PS:选择器应该是$(".results > div").(固定的)

回答by Paul

Alert the id property of the div:

提醒 div 的 id 属性:

alert(this.id);