我有2个div(HTML)元素,id为div1和div2,当我单击任何div时,我想要当前div的ID ...这个主意吗?
<div id="div1"></div>
<div id="div2"></div>
<div id="displayid"></div>
if(clickedDivId = this.id){
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId;
for (var i = 0; i < divCount; i += 1) {
div[i].onclick = function(e) {
clickedDivId = this.id;
event.stopPropagation();
};
}
}
document.getElementById("displayid").innerHTML = ??clickedDivId??how;
答案 0 :(得分:0)
使用this.id
来获得id
的点击格。
document.querySelectorAll('div')
.forEach(div => {
div.addEventListener('click', function() {
console.log(this.id);
})
})
<div id="div1">Div 1</div>
<div id="div2">Div 2</div>
<div id="displayid">Div 3</div>
答案 1 :(得分:0)
document.addEventListener('click',function(e){
var divToDisplay = event.target.id
document.getElementById('displayid').innerHTML = divToDisplay
})
<div id="div1">DIV TEST 1</div>
<div id="div2">DIV TEST 2</div>
<div id="displayid"></div>
答案 2 :(得分:0)
尝试通过修改自己的代码
var div = document.getElementsByTagName("div");
var divCount = div.length;
var clickedDivId;
for (var i = 0; i < divCount; i += 1) {
div[i].onclick = function(e) {
e.stopPropagation();
clickedDivId = this.id;
document.getElementById("displayid").innerHTML = this.id;
};
}