jquery.parents()正在选择祖父母的祖父母和兄弟姐妹

Kyl*_*lee 2 html javascript jquery

我想要完成的是当用户专注于文本框时,其中的字段集将添加一个类"active_fieldset",因此它提供了一个很好的视觉提示,表明用户在表单中的位置.使用以下javascript,它确实会影响父字段集,但它也会影响所有兄弟字段集.难道我做错了什么?我的HTML或javascript是否存在根本性问题?

示例HTML:

<div id="content">

 <form action="next_page" method="post">

  <fieldset>
   <legend>Foo</legend>

   <p><label for="one">One</label> <input type="text" class="input_text" name="one" value="" id="one"></p>
  </fieldset>

  <fieldset>
   <legend>Bar</legend>

   <p><label for="two">Two:</label><input type="text" class="input_text" name="two" value="" id="two"></p>

  </fieldset>

  <p><input type="submit" value="Continue &rarr;"></p>
 </form>

</div>
Run Code Online (Sandbox Code Playgroud)

form.js:

$(document).ready(function(){
 $('.input_text').focus(function(){
  $(this).parents('fieldset').addClass("active_fieldset");
 });
});
Run Code Online (Sandbox Code Playgroud)

编辑:

我已经包含了我的CSS:

fieldset
{
    border-width: 10px 0 0 0;
    border-style: solid;
    border-color: #0D6EB8;
}

fieldset.active_fieldset
{
    border-width: 10px 0 0 0;
    border-style: solid;
    border-color: #0D6EB8;
}
Run Code Online (Sandbox Code Playgroud)

tva*_*son 5

尝试使用最接近的方法.您可能需要将其与更多代码配对,以确保已从所有其他字段集中删除该类.

$('.input_text').focus( function() {
    $('fieldset').removeClass('active_fieldset');
    $(this).closest('fieldset').addClass('active_fieldset');
});
Run Code Online (Sandbox Code Playgroud)

引用文档:

最接近的工作是首先查看当前元素以查看它是否与指定的表达式匹配,如果是这样,它只返回元素本身.如果它不匹配,那么它将继续遍历父项的父文档,直到找到与指定表达式匹配的元素.如果找不到匹配的元素,则不返回任何元素.