<button id="aa">增加<button>
<span id="cc"></span>
<button id="bb">减少<button>
span的初始值为00,当增加到30是恢复初始值, 当减少到00在减少变成30
<button id="aa">增加<button>
<span id="cc"></span>
<button id="bb">减少<button>
span的初始值为00,当增加到30是恢复初始值, 当减少到00在减少变成30
var change = function(num){
var span = document.getElementById('cc'),
spanNum = span.innerText*1;
spanNum += num;
if(spanNum > 30){
spanNum = 0;
}
if(spanNum < 0) {
spanNum = 30;
}
if(spanNum<10){
span.innerText = '0'+spanNum;
} else {
span.innerText = ''+spanNum;
}
}
document.getElementById('aa').addEventListener('click', function(e) {
change(1);
});
document.getElementById('bb').addEventListener('click', function(e) {
change(-1);
});
var num=0;
$("#cc").text("00");
$("#aa").on("click",function(){
num++;
if(num<=9){
$("#cc").text("0"+num);
}else{
$("#cc").text(num);
}
if(num>30){
num=0;
$("#cc").text("0"+num);
}
});
$("#bb").on("click",function(){
num--;
if(num<=9){
$("#cc").text("0"+num);
}else{
$("#cc").text(num);
}
if(num<0){
num=30;
$("#cc").text(num);
}
});
答案很全了啊,我就补个react的吧
//index.js
var SpanBox = React.createClass({
getDefaultProps: function () {
return {
count: 0
}
},
render: function () {
var temp = this.props.count;
if (temp < 10 && temp >= 0)
temp = '0' + temp
else if (temp < 0 && temp > -10)
temp = '-0' + Math.abs(temp);
return <div>{temp}</div>;
}
});
var MainBox = React.createClass({
increaseHandler: function () {
if (++this.state.count > 30)
this.setState({
count: 0
})
else
this.setState({
count: this.state.count
})
},
reduceHandler: function () {
if (--this.state.count < 0)
this.setState({
count: 30
})
else
this.setState({
count: this.state.count
})
},
getInitialState: function () {
return {
count: 0
}
},
render: function () {
return (
<div>
<button id="aa" onClick={this.increaseHandler}>增加</button>
<SpanBox count={this.state.count}/>
<button id="bb" onClick={this.reduceHandler}>减少</button>
</div>
)
}
})
React.render(<MainBox/>, document.body);
//html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script src="../lib/react.js"></script>
<title></title>
</head>
<body>
<script src="../build/index.js"></script>
</body>
</html>
//index.js用babel转一下再用
13 回答12.9k 阅读
7 回答2.1k 阅读
3 回答1.3k 阅读✓ 已解决
2 回答1.3k 阅读✓ 已解决
6 回答1.2k 阅读✓ 已解决
6 回答1.1k 阅读
3 回答1.3k 阅读✓ 已解决
想了想还是不要直接绑定事件了,这样的写法一点营养都没有。
HTML
script