我有一个要验证的输入:
<input type="text" id="input" />
这是JS:
jQuery("#input").live('change', function() {
if("#input:not(:empty)") {
alert('not empty');
}
else if("#input:empty") {
alert('empty');
}
});
即使“ #input”为空,也无法通过“空”消息显示警报。因此,基本上,无论我做什么,始终总是只有第一个陈述是正确的,第二个陈述是错误的。
怎么了?
实际上,有一种更简单的方法可以做到:
JQuery's :empty selector selects all elements on the page that are empty in the sense that they have no child elements, including text nodes, not all inputs that have no text in them.
Jquery: How to check if an input element has not been filled in.
这是从上述线程窃取的代码:
This works because an empty string in JavaScript is a 'falsy value', which basically means if you try to use it as a boolean value it will always evaluate to
false
. If you want, you can change the conditional to$(this).val() === ''
for added clarity. :D你可以这样做
http://jsfiddle.net/jasongennaro/Y5P9k/1/
When the input has lost
focus
that is.blur()
, then check the value of the#input
.If it is empty
== ''
then trigger the alert.