我是JS / jQuery的新手,并使用以下代码尝试实现:
<a>
)以更改<input>
值<input>
输入一些数字到目前为止,一切都按计划进行,但
当我在<input>
以下是 keyup 代码
的部分内容$(document).on("keyup", "#buy-num", function(event){
event.preventDefault();
var t = $.trim( $buynum.val() );
console.log(t);
if( isNaN(Number(t)) || isEmpty(Number(t)) || isFloat(Number(t)) || Number(t) > 99 || Number(t) < 1 ){
alert("Please input 1~99 ");
}else{
$buynum.attr("value", Number(t));
}
console.log("test");
// event.stopImmediatePropagation();
});
答案 0 :(得分:4)
您希望使用$.val()
而非$.attr('value')
更新元素。
$(document).ready(function(){
var $add = $("#btn-add");
var $reduce = $("#btn-reduce");
var $buynum = $("#buy-num");
var count = Number($buynum.val());
$(document).on("click", "#btn-add", function(event){
event.preventDefault();
var count = Number($buynum.val());
var number = count + 1;
if (number >= 199){
$add.addClass("disabled");
$reduce.removeClass("disabled");
$buynum.val(199);
} else {
$add.removeClass("disabled");
$buynum.val(number);
}
// event.stopImmediatePropagation();
// return false;
});
// reduce
$(document).on("click", "#btn-reduce", function(event){
event.preventDefault();
var count = Number($buynum.val());
var number = count - 1;
if (number <= 1){
$buynum.val(1);
$reduce.addClass("disabled");
$add.removeClass("disabled");
} else {
$reduce.removeClass("disabled");
$buynum.val(number);
}
// event.stopImmediatePropagation();
// return false;
});
// onkeyup
$(document).on("keyup", "#buy-num", function(event){
event.preventDefault();
var t = $.trim( $buynum.val() );
console.log(t);
// if ( isNaN(Number(t)) || t.length==0 || isFloat(Number(t)) || Number(t) > 199 || Number(t) < 1 ) {
if ( isNaN(Number(t)) || isEmpty(Number(t)) || isFloat(Number(t)) || Number(t) > 199 || Number(t) < 1 ) {
alert("请输入 1~199 之间的整数");
} else {
$buynum.val(Number(t));
}
console.log("test");
return
// event.stopImmediatePropagation();
});
});
function isEmpty(t){
return "" == $.trim(t)
}
function isFloat(t){
return Number(t) === t && t % 1 !== 0
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="text buy-num" id="buy-num" value="1">
<a class="btn-reduce" id="btn-reduce" name="btn-reduce" href="#none">-</a>
<a class="btn-add" id="btn-add" name="add" href="#none">+</a>