我试图在文本框中输入内容时启用 img 按钮。但在文本框失去焦点后它正在工作。如何立即看到变化?
$("[id$='txtNewPass2']").change(function () {
if (myPlugin.metReq() == true && $("[id$='txtNewPass2']").val().length > 0) //return true or false
$("#imgSubmit").removeAttr("disabled").css('opacity', 1);
else
$("#imgSubmit").attr("disabled", "disabled").css('opacity', 0.5);
});
最佳答案
使用keyup
input
事件。
$("[id$='txtNewPass2']").on('input', function () {
if (myPlugin.metReq() == true && $("[id$='txtNewPass2']").val().length > 0) //return true or false
$("#imgSubmit").removeAttr("disabled").css('opacity', 1);
else
$("#imgSubmit").attr("disabled", "disabled").css('opacity', 0.5);
});
推荐使用 keyup
而不是 keydown
的原因是,在下面的代码片段中,如果您使用 keydown
事件将始终落后一个字母。
更新:
在尝试了我下面创建的示例之后。我可以看到 input
事件创建了更加平滑的更新效果。请参阅下面的示例,了解这三种方法的工作原理对比
示例:
$('#keyup-input').on('keyup', function () {
$('#keyup-div').html($('#keyup-input').val());
});
$('#keydown-input').on('keydown', function () {
$('#keydown-div').html($('#keydown-input').val());
});
$('#input-input').on('input', function () {
$('#input-div').html($('#input-input').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Keyup:</h1>
<input id="keyup-input" type="text" />
<div id="keyup-div"></div>
<br/>
<br/>
<h1>Keydown:</h1>
<input id="keydown-input" type="text" />
<div id="keydown-div"></div>
<br/>
<br/>
<h1>Input:</h1>
<input id="input-input" type="text" />
<div id="input-div"></div>
关于javascript - 文本框更改事件不会立即影响 jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26172593/