2011-11-10 78 views
0

我有特定的CSS通過我隱藏圖像。現在,我想開發jQuery的通過,如果特定字段是模糊比應該顯示類錯誤的圖像空白..更改圖像屬性使用jQuery

.error{ 
display:none; 
} 


<tr> 
    <th width="30%">Email:</th> 
    <td width="63%"><input type="text" name="email" id="email" title="Email*" class="validate"/></td> 
    <td width="05%"><img width="27" height="27" id="erroremail" src="images/error.png" alt="Error" title="N/A*" class="error"></td> 
</tr>.. 

我開發的jQuery這是

$('.validate').blur(function() { 
    if ($(this).val() == '') { 

     $(this).next('.error').show().css({'display':'block'}); 
       alert("null"); 

    } else { 

     $(this).next('.error').hide(); 
     alert("not null"); 
     } 
}); 

我雖然不是在控制檯上發生任何錯誤。即使警報也在運行,但jquery無法正常工作。

+0

您是否綁定了jQuery就緒事件中的blur事件(即在DOM被加載後)?當然是 – Chandu

+0

......我已經做到了。 –

回答

2

next()返回緊接兄弟節點。

在你的情況下,沒有用於.validate元素的兄弟,而是你想要定位的elamenet在下一個表格單元格中。

您必須使用$('.error', $(this).parent().next())才能獲得.error元素。

1)$(this).parent() - 返回父代td元素。
2)next()返回下一個td單元格。
3)$(".validate", $(this).parent().next())返回所有具有驗證類的元素,它們是$(this).parent().next()的子元素。

$('.validate').blur(function() {  
    if ($(this).val() == '') {   
     $('.error', $(this).parent().next()).show(); 
     alert("null");  
    } else {   
     $('.error', $(this).parent().next()).hide(); 
     alert("not null");   
    } 
}); 
+0

請解釋一下.. –

+0

添加了一些信息..林梅知道如果它不清楚。 – Chandu

2

您的代碼找不到合適的元素。試試這個:

$('.validate').blur(function() { 
    if ($(this).val() == '') { 

     $(this).closest('tr').find('.error').show(); 
       alert("null"); 

    } else { 

     $(this).closest('tr').find('.error').hide(); 
     alert("not null"); 
     } 
}); 

代碼:http://jsfiddle.net/6dWFs/

2

next()點什麼,因爲你在一個表是。首先選擇親本細胞,然後選擇.error元件:

$(this).parents('td:first').next().find('.error') 

最終代碼:

$('.validate').blur(function() { 
    var errorImg = $(this).parents('td:first').next().find('.error'); 
    if ($(this).val() == '') { 
     errorImg.show().css({'display':'block'}); 
       alert("null"); 
    } else { 
     errorImg.hide(); 
     alert("not null"); 
    } 
});