如何使用纯javascript

时间:2017-05-30 03:04:19

标签: javascript html css

我希望通过点击它来获取<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");
        }
     }

代码在这里:http://jsfiddle:%20http://jsfiddle.net/mm07p5rz/

2 个答案:

答案 0 :(得分:3)

只需获取点击事件id对象的target属性即可。顺便说一句,id s在文档中应该是唯一的。

这将获得点击页面上任何元素的id

&#13;
&#13;
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;
&#13;
&#13;

这将获得所点击的任何id元素的<a>。您可以按照自己喜欢的方式过滤特定元素,但获取id的过程是相同的:

&#13;
&#13;
// 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;
&#13;
&#13;

答案 1 :(得分:0)

我编辑您的源代码

&#13;
&#13;
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;
&#13;
&#13;