我试图循环遍历表单中的所有输入,如果输入不包含值,则执行一些操作。jquery each()函数不按预期工作
这里是我的代码,到目前为止,
$('input').each(function() {
if($(this+'[value!=""]')) {
$('.requiredMark').hide();
$(this).after(checkMark);
}
});
我在做什么错?谢谢
我试图循环遍历表单中的所有输入,如果输入不包含值,则执行一些操作。jquery each()函数不按预期工作
这里是我的代码,到目前为止,
$('input').each(function() {
if($(this+'[value!=""]')) {
$('.requiredMark').hide();
$(this).after(checkMark);
}
});
我在做什么错?谢谢
if-statement是错误的。 this
不会引用字符串。使用.val()以获得值:
$('input').each(function(){
var $this = $(this);
if($this.val() != "") {
$('.requiredMark').hide();
$this.after(checkMark);
}
});
这应该有所斩断。
$('input').each(function(){
if($(this).val()){
$('.requiredMark').hide();
$(this).after(checkMark);
}
});
您可以$(this)
访问您的输入字段,以获取其价值的$(this).val()
而不是做$(这+ '[价值!= “”]'),你可以使用
if($(this).val()===''){
//if the element has empty value, do something here
}
另外,如果你想检查空格,你可以做$(this).val()。trim() – 2013-05-02 20:50:06
$('input').val(function(index,el){
if(el.length){
alert('Has value')
}
});
那么,你现在的代码有什么问题?它什么都不做?发生错误?崩溃你的电脑?让飞行的猴子从天上坠落?给你免费的华夫饼?请澄清。 – Doorknob 2013-05-02 20:46:09
'这里'不是一个字符串,但你似乎认为它是。 – apsillers 2013-05-02 20:46:41
您的'if'陈述完全错误。 – SLaks 2013-05-02 20:46:48