我想将此代码设为DRY。我知道我在这里重复自己,必须有一种方法来压缩此代码。该代码可以正常工作,并且可以满足我的要求,但是我正在尝试学习如何更好地配置代码。你能帮忙吗?
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 - Javascript帮我做这个,所以很干,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33114457/