2013-02-08 144 views
0

我在頁面上有幾個表單,每個表單都有自己的「消息框」,顯示驗證錯誤。每個「消息框」都有一個關閉按鈕。我沒有問題讓關閉按鈕關閉「消息框」,但我也需要它從有問題的文本輸入中刪除類「錯誤」。頁面內容是由ajax引入的,因此「.on」就是「.on」遍歷DOM並刪除類

僞HTML(請記住,這些全部都包含在它們自己的表單標籤中,其中8個是消息框和關閉按鈕的一部分。

<form action="#" method="post" id="Form6"> 
    <ul> 
     <li> 
      <label for="foo">label</label> 
      <input type="text" name="foo" id="foo"> 
      <input type="submit" id="Button6" value="submit" /> 
     </li> 
    </ul> 
    <div id="Msg6" class="error"><a class="close">X</a><ul></ul></div> 
</form> 

我嘗試

$('body').on('click', 'a.close', function(){ 
    $(this).parent().fadeOut("fast"); 
    $(this).closest('input[type="text"].error').removeClass('error'); // doesn't work 
    $('a.close').closest('ul > li > input.error').remove();// doesn't work 
    //console.log($.closest('input[type="text"].error'));//tring to log the value of the ancestor 
}); 

回答

1

這應該工作:

$(this).parents('form').find('input.error').removeClass('error'); 

但是,如果你想刪除它,無需更改類,只需使用.remove() ...

+0

完美。所以你遍歷DOM的父窗體,然後找到input.error和removeClass。經驗教訓先生。只需使用remove來獲得基線,意圖是刪除類。 – 2013-02-08 23:44:14

+0

是的,但你也可以使用「最接近」而不是「父母」。我認爲這樣會更快,因爲'nearest()'會回溯到找到匹配,而'parents()'會收集所有父母,然後查找匹配 – 2013-02-08 23:54:49