[英]How would I make the color of squares change when they are clicked using Javascript?
I have written it out using an event listener but it does not work and the squares remain black even when they are clicked.我已经使用事件侦听器将它写出来,但它不起作用,即使单击它们,方块仍然是黑色的。 I found a few typos that I fixed but I am not sure whether I was correct in using getElementsByClassName
.我发现了一些拼写错误,但我不确定我使用getElementsByClassName
是否正确。
html: html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.square {
width: 100px;
height: 100px;
background-color: #000000;
margin: 5px;
}
</style>
</head>
<body>
<div id="container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<script src="js/main.js"></script>
</body>
</html>
and Javascript:和 Javascript:
var squares = document.getElementsByClassName('square');
for(var i = 0; i < squares.length; i++) {
squares[0].addEventListener("click", changeColor);
}
function changeColor(event) {
event.style.backgroundColor = randomColor();
}
function randomColor() {
var randomRed = Math.floor(Math.random() * 255);
var randomGreen = Math.floor(Math.random() * 255);
var randomBlue = Math.floor(Math.random() * 255);
//create the string that is the ‘random color’
var randomColor = "rgb("+randomRed+","+randomGreen+","+randomBlue+")";
return randomColor;
}
Two basic problems:两个基本问题:
squares[0]
when it should be squares[i]
, so you're binding the handler to the first element multiple times and not to the others.你的 for 循环有一个硬编码的squares[0]
当它应该是squares[i]
,所以你多次将处理程序绑定到第一个元素而不是其他元素。event
object doesn't have a style
property. event
对象没有style
属性。 Use this.style.backgroundColor
- within the handler this
will refer to the clicked element.使用this.style.backgroundColor
- 在处理程序中, this
将引用被点击的元素。 Or use event.target.style.backgroundColor
.或者使用event.target.style.backgroundColor
。So like this:所以像这样:
for(var i = 0; i < squares.length; i++) {
squares[i].addEventListener("click", changeColor);
}
function changeColor(event) {
this.style.backgroundColor = randomColor();
}
Demo: http://jsfiddle.net/oueLs5dp/演示: http : //jsfiddle.net/oueLs5dp/
The answer is very simple.答案很简单。 My codepen of the below changes working as intended.我对以下更改的代码笔按预期工作。 : http://codepen.io/anon/pen/MwgEdm : http : //codepen.io/anon/pen/MwgEdm
First, you need to modify your for loop, you are referencing index 0 instead of i:首先,您需要修改 for 循环,您引用的是索引 0 而不是 i:
for(var i = 0; i < squares.length; i++) {
squares[i].addEventListener("click", changeColor);
}
Second, you need to reference 'this' within your change color function, and pass in e for the event object:其次,您需要在更改颜色函数中引用“this”,并为事件对象传入 e:
function changeColor(e) {
this.style.backgroundColor = randomColor();
}
Using .addEventListener()
you would need to change:使用.addEventListener()
你需要改变:
function changeColor(event) {
event.style.backgroundColor = randomColor();
}
to到
function changeColor(){
// not using Event Object
this.style.backgroundColor = randomColor();
}
, but let's face it .getElementsByClassName()
is not backward compatible anyways. ,但让我们面对.getElementsByClassName()
吧.getElementsByClassName()
无论如何都不向后兼容。
I recommend the following:我推荐以下内容:
var doc = document, bod = doc.body;
function E(e){
return doc.getElementById(e);
}
function inArray(x, a){
for(var i=0,l=a.length; i<l; i++){
if(a[i] === x){
return true;
}
}
return false;
}
function getElementsByClass(className, element){
var r = false;
var el = element ? element : doc;
if(el.getElementsByClassName){
r = el.getElementsByClassName(className);
}
else{
var all = el.getElementsByTagName('*'), l = all.length;
if(l > 0){
r = [];
for(var i=0; i<l; i++){
var s = all[i].className.split(/\s/);
if(inArray(className, s))r.push(all[i]);
}
}
return r;
}
function randomColor(context){
context.style.backgroundColor = 'rgb('+Math.floor(Math.rand()*256)+','+Math.floor(Math.rand()*256)+','+Math.floor(Math.rand()*256)+')';
}
Now it's like:现在是这样的:
var all = getElementsByClass('square');
for(var i=0,l=all.length; i<l; i++){
(function(i){ // in case you want to add more array stuff
all[i].onclick = function(){
randomColor(this);
// do more stuff here
}
})(i); // end of closure
}
Note: Math.random()
returns a number between 0 and .9 repeating, never 1. You'll never get 255 with your current formula.注意: Math.random()
返回一个介于 0 和 .9 之间的重复数字,永远不会是 1。使用当前公式,您永远不会得到 255。
You should use JQuery to do this, it is relatively easy.你应该使用 JQuery 来做到这一点,它相对容易。 put this link between your head tags: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
And then put this code in your javascript:将此链接放在您的 head 标签之间: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
然后将此代码放入你的javascript:
$(document).ready(function(){
$('.square').click(function(){
$('.square').addClass('green');
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.