javascript onclick 获取 div id?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30112838/
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
javascript onclick get the div id?
提问by sa.lva.ge
Is it possible to get the ids of the 2 div tags on clicking the button, using javascript?
是否可以使用 javascript 在单击按钮时获取 2 个 div 标签的 ID?
<div id="main">
<div id="content">
</div>
<button onclick="function();">show it</button>
</div>
I have 2 div tags here. The 1st div is in the main div while the content div is inside the main div and the button is inside the main div as well.
我这里有 2 个 div 标签。第一个 div 在主 div 中,而内容 div 在主 div 内,按钮也在主 div 内。
Is it possible to get the mainand contentid of the 2 div tags on clicking the button?
单击按钮是否可以获取2 个 div 标签的主ID和内容ID?
EXPECTED OUTPUT when I press the button:
当我按下按钮时的预期输出:
alert: main alert: content
alert: main alert: content
回答by Barmar
You need to pass the element to the function. Then you can use parentNodeto get the DIVthat contains the button. From there, you can use querySelectorto find the first DIVin the parent.
您需要将元素传递给函数。然后您可以使用parentNode来获取DIV包含该按钮的 。从那里,您可以使用在父级中querySelector查找第一个DIV。
function showIt(element) {
var parent = element.parentNode;
alert(parent.id);
var content = parent.querySelector("div");
alert(content.id);
}
<div id="main">
<div id="content">
</div>
<button onclick="showIt(this);">show it</button>
</div>
<div id="main2">
<div id="content2">
</div>
<button onclick="showIt(this);">show it</button>
</div>
<div id="main3">
<div id="content3">
</div>
<button onclick="showIt(this);">show it</button>
</div>
回答by frontsideup
This should work in all browsers and uses the cleaner .idmethod.
这应该适用于所有浏览器并使用更清洁的.id方法。
var button = document.getElementById('button');
button.onclick = getIDs;
function getIDs(){
var id,divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
id = divs[i].id // .id is a method
alert(id);
}
}
<div id="main">
<div id="content"></div>
<button id="button">show it</button>
</div>
回答by Miguel Mota
document.getElementById('button').onclick = function () {
var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
var id = divs[i].getAttribute('id');
alert(id);
}
};

