我在基于 jQuery 中的 if/else 语句启用和禁用按钮时遇到问题。这里的问题是,当文本输入获得焦点时,该按钮立即启用。该代码似乎忽略了 if 语句中的参数。显然,这不是我想要制作的应用程序,但我编写了这段代码来测试网站中无法正常工作的部分。有什么建议吗?
这是 HTML
<input type="text" id="type_here" />
<input type="button" id="test_button" value="test" disabled/>
这是 JavaScript
$(document).ready(function () {
$(document).click(function () {
if ($('#type_here').val !== "") {
$('#test_button').prop('disabled', false);
} else {
$('#test_button').prop('disabled', true);
}
}).keyup(function () {
if ($('#type_here').val !== "") {
$('#test_button').prop('disabled', false);
} else {
$('#test_button').prop('disabled', true);
}
});
});
最佳答案
试试这个:-
您正在使用 .val
而不是 .val()
.val 始终会返回函数引用而不是函数的结果。所以你的陈述永远是正确的。
$(document).ready(function () {
$(document).click(function () {
$('#test_button').prop('disabled', $('#type_here').val() === "");
}).keyup(function () {
$('#test_button').prop('disabled', $('#type_here').val() === "");
});
});
关于jQuery prop 不能作为 if 语句的一部分工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16387092/