gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 15:26:17 25 4
gpt4 key购买 nike

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

表单.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com