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