javascript - jquery.parents() 正在选择祖 parent 和祖 parent 的 sibling

标签 javascript jquery html

我想要完成的是,当用户将焦点放在文本框上时,其中的字段集将添加一个“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>

form.js:

$(document).ready(function(){
 $('.input_text').focus(function(){
  $(this).parents('fieldset').addClass("active_fieldset");
 });
});

编辑:

我已经包含了我的 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;
}

最佳答案

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

$('.input_text').focus( function() {
    $('fieldset').removeClass('active_fieldset');
    $(this).closest('fieldset').addClass('active_fieldset');
});

引用文档:

Closest works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression. If no matching element is found then none will be returned.

关于javascript - jquery.parents() 正在选择祖 parent 和祖 parent 的 sibling ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1451049/

相关文章:

html - 为容器设置 CSS 渐变

javascript - 阻止了源为 "http://localhost:8084"的框架访问跨域框架

javascript - 获取过去 24 小时内 BTC 的 yield /损失百分比 - Coinbase

javascript - 确定单击后 JQuery 对话框操作无法正常工作

javascript - 无框模态弹出

javascript - 如何让带有 false animate 队列的 onClick 函数也运行外部函数?

javascript - 有没有人使用 webworker 并行化在 JavaScript 中进行过大型搜索?

javascript - 用 Javascript/JQuery 替换和添加包装器

javascript - 谷歌地图信息窗口关闭不起作用

javascript - 为多个页面和按钮添加事件监听器