2011-02-04 100 views
0

我试图编写代码,如果焦点已经离开文本字段的类为“强制性”,并且该字段为空,则会发出警报声。jQuery类选择器问题

基本上,如果用户在不写任何内容的情况下离开强制文本字段,它会提示他们。

这里是我的代码,这是行不通的:

$(document).ready(function(){ 
     $('.mandatory').blur(function(){ 
      if($(this.id).val() == "") 
      { 
        alert('Field:' + this.id + ' is mandatory!'); 
      } 
     }); 
    }); 

回答

2

您使用this.id时,你应该使用this

if($(this).val() == "") 
{ 
    alert('Field:' + this.id + ' is mandatory!'); 
} 

要解释一下:在事件处理中,this是事件被触发的DOM元素。正如你可以从$函数的文档中看到的(注意jQuery函数和$函数是一样的),你可以使用DOM元素来构建一个jQuery选择。

请注意,您可以通过丢弃jQuery构造函数并简单地使用this.value来进一步优化它。

1

假设你正在使用jQuery:

$(document).ready(function(){ 
    $('.mandatory').blur(function(){ 
     if($(this).val() == "") { 
      alert('Field:' + $(this).attr('id') + ' is mandatory!'); 
     } 
    }); 
}); 
+1

[见这里演示(http://jsfiddle.net/Scoobler/K3GCT/) – Scoobler 2011-02-04 08:51:33

1

您的代码习惯,如果用户输入了工作的空白

使用

$ .trim()

改为

$(document).ready(function(){ 
     $('.mandatory').blur(function(){ 
      if($.trim($(this).val()) == "") 
      { 
        alert('Field:' + this.id + ' is mandatory!'); 
      } 
     }); 
    }); 
0

猜你试着这样做

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script> 

<script> 
$(function(){ 
    $('.mandatory').each(function(){ 
     $(this).blur(
     function(){ 
      if($(this).val() == ""){ 
       alert("empty"); 
      } 
     }) 
    }); 

}); 
</script> 


<div id='header'> 
<input type="text" class="mandatory"/> 
<input type="text" class="mandatory"/> 
<input type="text" class="mandatory"/> 
<input type="text" class="mandatory"/> 
<input type="text" class="mandatory"/> 
<input type="text" class="mandatory"/> 
<input type="text" class="mandatory"/> 
</div> 

,这是工作