gpt4 book ai didi

jquery - 优化代码以将 css 类添加到父 div

转载 作者:行者123 更新时间:2023-12-01 01:07:12 26 4
gpt4 key购买 nike

我正在尝试向父 div 添加一个类,即 <div class="form-group">我让它工作了,但想知道是否有更短或更简单的方法来做到这一点?这是我的 2 个 HTML 情况

HTML:

<div class="form-group">
<label class="col-md-3 control-label required" for="Comment_postcode">Your Postcode <span class="required">*</span></label>
<div class="col-md-9 error">
<span style="position: relative; display: inline-block;" class="twitter-typeahead">
<input style="position: absolute; top: 0px; left: 0px; border-color: transparent; box-shadow: none; background: none repeat scroll 0% 0% rgb(255, 255, 255);" class="tt-hint" autocomplete="off" spellcheck="off" disabled="" type="text"/>
<input dir="auto" style="position: relative; vertical-align: top;" spellcheck="false" autocomplete="off" class="form-control tt-query" name="Comment[postcode]" id="Comment_postcode" type="text"/>
</span>
</div>
</div>

<div class="form-group">
<label class="col-md-3 control-label required" for="Comment_purchased">This vehicle was purchased <span class="required">*</span>
</label>
<div class="col-md-9 error">
<select id="Comment_purchased" class="form-control input-md">
<option value="">Select One</option>
<option value="1">New</option>
<option value="2">Used</option>
</select>
<div class="errorMessage" id="Comment_purchased_em_" style="display:none">Purchased cannot be blank.</div>
</div>
</div>

这是我添加或删除 has-error 类的 JQuery 代码

if (i != "Comment_postcode") {
$("#"+i).parent("div").parent("div").addClass("has-error");
} else {
$("#"+i).parent("span").parent("div").parent("div").addClass("has-error");
}

我该如何优化上面的代码?如果可能的话,无需 if-else 语句。谢谢

最佳答案

使用closest 获取最接近的父级

 $("#"+i).closest(".form-group").addClass("has-error");

Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

关于jquery - 优化代码以将 css 类添加到父 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25278496/

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