我有一个jquery函数,如果选择了一个可以正常运行的选项,它会阻止用户写字符,但问题是当我选择另一个允许字符阻止它的选项时,我尝试添加event.stopPropagation()at结束但它似乎不起作用。我是javascript的新手
$('select').on('change', function () {
var thisPrice = '';
switch (this.value) {
case '1':
thisPrice = 2;
break;
case '2':
$(".allownumericwithoutdecimal").on("keypress keyup blur",function (event) {
$(this).val($(this).val().replace(/[^\d].+/, ""));
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
break;
case '3':
event.preventDefault();
thisPrice = 5;
break;
case '4':
thisPrice = 6;
break;
}
$('#showPrice').val(thisPrice);
});
<select>
<option>Choose size</option>
<option id="size1">1</option>
<option id="size2">2</option>
<option id="size3">3</option>
<option id="size4">4</option>
</select>
<input class="allownumericwithoutdecimal" type="text" id="showPrice" />
答案 0 :(得分:4)
您必须在函数开头插入以下代码行:
$('select').on('change', function () {
var thisPrice = '';
$(".allownumericwithoutdecimal").off("keypress keyup blur");
//...
});
当您添加.on(...)
这样的事件处理程序时,如果要删除它,则必须使用.off(...)
方法。
答案 1 :(得分:0)
为什么不只是为输入设置一个监听器来读取选择,然后对其进行处理呢?
你这样工作:
//'input' and 'select'
$('select').on('change', function(e){
if($(this).val) == something){
$('input').on('change', function(){
//add new listener based on select option.
});
}
});
当你可以像这样工作时:
//Just one listener needs to be added.
$('input').on('change', function(){
var selectVal = $('select').val();
if(selectVal == 1){
//do something based on select value.
doSomething();
} else {
doSomethingElse();
}
});
使用第一种方式,每次更改选项时都必须删除附加的侦听器,使用第二种方式只需要一个侦听器。