通过javascript

时间:2018-04-15 18:16:30

标签: javascript onclick

这些代码不起作用。

var x = document.getElementsByClassName("circle");
for (var i = 0; i < x.length; i++) {
    x[i].onclick = function(){ alert("hello!");};
}

2 个答案:

答案 0 :(得分:1)

&#13;
&#13;
var x = document.getElementsByClassName("circle");
for (var i = 0; i < x.length; i++) {
  x[i].onclick = function() {
    this.style.opacity = 0
  };
}
&#13;
.circle {
  width: 100px;
  height: 100px;
  background: red;
  border-radius: 50%;
  margin: 20px;
  float: left;
  transition: all .3s linear;
}
&#13;
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

这样做更好:

for ( i = 0; i < x; i++) {
   x[i].addEventListener('click', function() { alert('Hello World') });
}