我有一个带文本的HTML文档.我想做到的是,当你点击一个上div元素,在id那div所示.
我试过这个:
window.onload = function() {
associateIds();
clicked();
}
function associateIds() {
var all = document.getElementsByTagName("*");
var id = -1;
for (var elem = 0; elem < all.length; elem++) {
if (all[elem].tagName == "DIV") {
id++;
all[elem].setAttribute("id", id);
}
}
}
function clicked() {
document.body.onclick = function(evt) {
var evt = window.event || evt; //window.event for IE
if (!evt.target) {
evt.target = evt.srcElement; //extend target property for IE
}
alert(evt.target.id);
}
}Run Code Online (Sandbox Code Playgroud)
<div>
<h1>MAIN …Run Code Online (Sandbox Code Playgroud)