我有一个输入要验证:
<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“为空,也无法显示带有" empty”消息的警报。所以,基本上,无论我做什么,只有第一个陈述是真的,第二个是假的,总是。
怎么了?
发布于 2011-07-23 23:47:53
选择页面上所有为空的元素,因为它们没有子元素,包括文本节点,而不是其中没有文本的所有输入。
下面是从上面的线程中窃取的代码:
$('#apply-form input').blur(function() //whenever you click off an input element
{
if( !$(this).val() ) { //if it is blank.
alert('empty');
}
});这之所以有效,是因为JavaScript中的空字符串是“falsy值”,这基本上意味着如果您尝试将其用作布尔值,它将始终计算为false。如果需要,您可以将条件更改为$(this).val() === ''以增加清晰度。:D
发布于 2011-07-23 23:48:46
你可以这样做
$("#input").blur(function(){
if($(this).val() == ''){
alert('empty');
}
});http://jsfiddle.net/jasongennaro/Y5P9k/1/
当输入丢失为.blur()的focus时,请检查#input的值。
如果== ''为空,则触发警报。
发布于 2011-07-23 23:48:58
jQuery("#input").live('change', function() {
// since we check more than once against the value, place it in a var.
var inputvalue = $("#input").attr("value");
// if it's value **IS NOT** ""
if(inputvalue !== "") {
jQuery(this).css('outline', 'solid 1px red');
}
// else if it's value **IS** ""
else if(inputvalue === "") {
alert('empty');
}
});https://stackoverflow.com/questions/6801483
复制相似问题