gpt4 book ai didi

javascript - Jquery 选择包含目标的 div

转载 作者:行者123 更新时间:2023-11-28 10:58:43 25 4
gpt4 key购买 nike

<div class="row">
<label for="txtTitle">Title</label>
<div class="holder">
<div class="text-holder"> <span class="ico-error"></span><span class="text"> <input id="txtTitle"
runat="server" type="text" value="" /></span> <span class="t-l">
</span><span class="b-l"></span><span class="t-r"></span><span class="b-r"></span>
</div>
</div>
</div>

我有以下 html。我计划对输入框进行一些 Jquery 验证。如果这是无效的,我想将错误类添加到 div

        var isValid = true;
var errorMessage = '';
if ($('#<%=txtTitle.ClientID %>').val() == '') {
$('#<%=txtTitle.ClientID %>').parent().parent().parent(".row").addClass("error");
isValid = false;
errorMessage += "Firstname is required\n";
}
return isValid;

我尝试以父级为目标,但发现该 div 位于父级层次结构的更上方。因此尝试选择具有更多父标签的层次结构,但我认为我偏离了理解定位 div 的正确方法的方向。

最佳答案

我建议使用.closest() :

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.

var isValid = true;
var errorMessage = '';
var $this = $('#<%=txtTitle.ClientID %>');

if ($this.val() == '') {
$this.closest(".row").addClass("error");
isValid = false;
errorMessage += "Firstname is required\n";
}
return isValid;

关于javascript - Jquery 选择包含目标的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14363378/

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