我创建了一个简单的随机颜色生成器应用程序。障碍是,即使在任何点击事件发生之前,也会自动点击通过javascript创建的按钮。我是javascript的新手 这是我的整个代码。提前谢谢。
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function btn(){
var cgen = document.createElement('button');
cgen.innerHTML = 'Generate';
document.body.appendChild(cgen);
cgen.style.width = '100%';
cgen.style.fontSize = '20px';
cgen.style.border = '2px solid red';
cgen.onclick = paintDivs();
// cgen.setAttribute("onclick", paintDivs());
}
function genColor(){
var randomColor = "#" + Math.floor(Math.random()*16777215).toString(16);
return randomColor;
}
function paintDivs(){
for (var i = 0; i < 500; i++) {
var fColor = genColor();
var bColor = genColor();
var div = document.createElement('div');
div.innerHTML = 'Text ' + fColor + ' Back ' + bColor;
div.style.color = fColor;
div.style.background = bColor;
div.style.width = '24%';
div.style.float = 'left';
div.style.margin = '5px';
div.style.height = '60px';
div.style.fontSize = '18px';
div.style.lineHeight = '60px';
div.style.textAlign = 'center';
div.style.borderRadius = '20px';
document.body.appendChild(div);
}
}
</script>
</head>
<body onload="btn();" style="background-color: gray;">
</body>
</html>
</html>
答案 0 :(得分:4)
cgen.onclick = paintDivs();
立即调用paintDivs()
并将cgen.onclick
设置为其返回值。你想要的是这个:
cgen.onclick = paintDivs;
答案 1 :(得分:0)
尝试以下代码。 有变化cgen.onclick = paintDivs();到cgen.onclick = paintDivs;
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript">
function btn(){
var cgen = document.createElement('button');
cgen.innerHTML = 'Generate';
document.body.appendChild(cgen);
cgen.style.width = '100%';
cgen.style.fontSize = '20px';
cgen.style.border = '2px solid red';
cgen.onclick = paintDivs;
// cgen.setAttribute("onclick", paintDivs());
}
function genColor(){
var randomColor = "#" + Math.floor(Math.random()*16777215).toString(16);
return randomColor;
}
function paintDivs(){
for (var i = 0; i < 500; i++) {
var fColor = genColor();
var bColor = genColor();
var div = document.createElement('div');
div.innerHTML = 'Text ' + fColor + ' Back ' + bColor;
div.style.color = fColor;
div.style.background = bColor;
div.style.width = '24%';
div.style.float = 'left';
div.style.margin = '5px';
div.style.height = '60px';
div.style.fontSize = '18px';
div.style.lineHeight = '60px';
div.style.textAlign = 'center';
div.style.borderRadius = '20px';
document.body.appendChild(div);
}
}
</script>
</head>
<body onload="btn();" style="background-color: gray;">
</body>
</html>
</html>