新手最简单的JS代码帮忙 不会就别说你是程序员!!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<body>
<span id="add1">+</span>
<input type="text" id="text1" class="item_quantity shulk" value="1" title="数量" />
<span id="reduce1">-</span><br>
<span id="add2">+</span>
<input type="text" id="text2" class="item_quantity shulk" value="1" title="数量" />
<span id="reduce2">-</span>
<span id="add3">+</span>
<input type="text" id="text3" class="item_quantity shulk" value="1" title="数量" />
<span id="reduce3">-</span>
<script>
function $(id){
return document.getElementById(id);
}
var elems1 = {
add: $("add1"),
reduce: $("reduce1"),
text: $("text1")
}
elems1.add.onclick = function(){
elems1.text.value++;
}
elems1.reduce.onclick = function(){
elems1.text.value--;
if(elems1.text.value<1)
{elems1.text.value=1;}
}
var elems2 = {
add: $("add2"),
reduce: $("reduce2"),
text: $("text2")
}
elems2.add.onclick = function(){
elems2.text.value++;
}
elems2.reduce.onclick = function(){
elems2.text.value--;
if(elems2.text.value<1)
{elems2.text.value=1;}
}
var elems3 = {
add: $("add3"),
reduce: $("reduce3"),
text: $("text3")
}
elems3.add.onclick = function(){
elems3.text.value++;
}
elems3.reduce.onclick = function(){
elems3.text.value--;
if(elems3.text.value<1)
{elems3.text.value=1;}
}
</script>
</body>
</html>
-------------------------以上是代码------------------------------
我想精简JS代码部分 最好是用循环语句的 这是最简单的问题,我是JS新手
求大神帮助!!多谢多谢!!
------解决方案--------------------function $(id) { return document.getElementById(id); }
var ele = { add: "add", reduce: "reduce", text: "text" };
for (var n = 1; n < 4; n++) {
$(ele.add + n).onclick = $(ele.reduce + n).onclick = function () {
var txt = $(ele.text + this.id.substr(this.id.length - 1, 1));
var val = parseInt(txt.value);
txt.value = this.id.startsWith(ele.add) ? val + 1 : val <= 1 ? 1 : val - 1;
};
}
基本可以说是最短代码了,替换你的script标签内所有代码即可