我希望通过点击它来获取<div>
或<a>
的ID。请帮忙......
<div class="reccl" id="allact"><a href="#" class="a" id="b">All Activities</a></div>
<div class="reccl" id="lgns"><a href="#" class="a" id="bb">Logins</a></div>
<div class="reccl" id="dwld"><a href="#" class="a" id="bb">Download</a></div>
javascript代码:
var a = document.getElementsByClassName('a');
for(var b = 0; b <= a.length; b++){
a[i].onclick = function(e){
alert("id clicked");
}
}
答案 0 :(得分:3)
只需获取点击事件id
对象的target
属性即可。顺便说一句,id
s在文档中应该是唯一的。
这将获得点击页面上任何元素的id
:
document.addEventListener("click", function(evt){
console.log(evt.target.id);
});
&#13;
<div class="reccl" id="allact"><a href="#" class="a" id="b">All Activities</a></div>
<div class="reccl" id="lgns"><a href="#" class="a" id="bb">Logins</a></div>
<div class="reccl" id="dwld"><a href="#" class="a" id="bbb">Download</a></div>
&#13;
这将获得所点击的任何id
元素的<a>
。您可以按照自己喜欢的方式过滤特定元素,但获取id
的过程是相同的:
// Get just and <a> elements
var anchors = document.querySelectorAll("a");
// Set up a click event listener for each one
for(var i = 0; i < anchors.length; i++){
anchors[i].addEventListener("click", function(evt){
console.log(evt.target.id);
});
}
&#13;
<div class="reccl" id="allact"><a href="#" class="a" id="b">All Activities</a></div>
<div class="reccl" id="lgns"><a href="#" class="a" id="bb">Logins</a></div>
<div class="reccl" id="dwld"><a href="#" class="a" id="bbb">Download</a></div>
&#13;
答案 1 :(得分:0)
我编辑您的源代码
var a = document.getElementsByClassName('reccl');
for (var b = 0; b < a.length; b++) {
a[b].onclick = function(e){
//get child's id in element
alert(e.target.id);
//get element's id
alert(e.currentTarget.id);
}
}
&#13;
<div class="reccl" id="allact"><a href="#" class="a" id="b">All Activities</a></div>
<div class="reccl" id="lgns"><a href="#" class="a" id="bb">Logins</a></div>
<div class="reccl" id="dwld"><a href="#" class="a" id="bb">Download</a></div>
&#13;