2013-02-08 148 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