.on( "change" ,function(){} 不要在里面调用函数


<script>
$("#text").on("change",function(){
var id =  $(this).val();
if(id!= ""){
$('#test').rules('remove',  'required');
}else{
$('#test').rules('add',  'required');
}
debugger;
SetIndicator(id);           
});
function SetIndicator(id){ do something..}
</script>

问题是当我更改"#text"时,它不会调用 SetIndicator(id(,但是当我刷新页面时,SetIndicator(id( 正常工作

对于 jsfiddle https://jsfiddle.net/76thdqcp/

问题是更改事件仅在文本输入的焦点"关闭"后才会触发。将代码更改为 keyup 事件可以解决您的问题。

$("#text").on("keyup", function() {
var id = $(this).val();
if (id) {
//$('#test').rules('remove', 'required');
} else {
//$('#test').rules('add', 'required');
}
SetIndicator(id);
});
function SetIndicator(id) {
console.log('id', id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text" />

$("#text").change(function(){
var id =  $(this).val();
if(id!= ""){
$('#text').attr('style',  'color:red');
}else{
$('#text').attr('style',  'color:yellow');
}
SetIndicator(id);           
});
function SetIndicator(id){
console.log(id); 
$("#test").html("Its working");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<input type="text" id="text" />
<div id="test"></div>

尝试下面的代码。

$("#text").change(function(){
var id =  $(this).val();
if(id!= ""){
$('#text').attr('style',  'color:red');
}else{
$('#text').attr('style',  'color:yellow');
}
SetIndicator(id);           
});
function SetIndicator(id){
alert("hi"); $("#test").html("Its working");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<input type="text" id="text" />
<div id="test"></div>

愿它对你有所帮助。

最新更新