gpt4 book ai didi

Javascript 帮我做这个,这样它就干了

转载 作者:行者123 更新时间:2023-12-03 08:38:53 26 4
gpt4 key购买 nike

我想让这段代码变得干燥。我知道我在这里重复自己,并且必须有一种方法来压缩这段代码。该代码正在运行并且可以执行我想要的操作,但我正在尝试学习如何更好地配置我的代码。你能帮忙吗?

http://codepen.io/anon/pen/GpMKLX

<div class="wrapper">
<div class="num_wrapper">
<div id="divNum_1"></div>
<button id="btn_1"> Pick</button>
</div>
<div class="num_wrapper">
<div id="divNum_2"></div>
<button id="btn_2"> Pick</button>
</div>
<div class="num_wrapper">
<div id="divNum_3"></div>
<button id="btn_3"> Pick</button>
</div>
<div class="num_wrapper">
<div id="divNum_4"></div>
<button id="btn_4"> Pick</button>
</div>
</div>

var btnOne = document.getElementById("btn_1");
var btnTwo = document.getElementById("btn_2");
var btnThree = document.getElementById("btn_3");
var btnFour = document.getElementById("btn_4");

var divOne = document.getElementById("divNum_1");
var divTwo = document.getElementById("divNum_2");
var divThree = document.getElementById("divNum_3");
var divFour = document.getElementById("divNum_4");

function randomNum() {
var num = Math.random() * 10;
num = Math.floor(num);
return num;
}

btnOne.onclick = function () {
divOne.innerHTML = randomNum();
}

btnTwo.onclick = function () {
divTwo.innerHTML = randomNum();
}

btnThree.onclick = function () {
divThree.innerHTML = randomNum();
}

btnFour.onclick = function () {
divFour.innerHTML = randomNum();
}

最佳答案

function addOnclick(index)
{
//Get the button
var button = document.getElementById( "btn_" + index );

//Add listener
button.addEventListener(
"click",
function () {
document.getElementById( "divNum_" + index ).innerHTML = randomNum();
}
);
}

//Now call it
for ( var i = 1; i < 5; i++ ) addOnclick( i );

Working JSFiddle

关于Javascript 帮我做这个,这样它就干了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33114457/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com