简体   繁体   English

jQuery选择包含目标的div

[英]Jquery select containing div of target

<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>

I have the following html. 我有以下html。 I am planning on doing some Jquery validation on the input box. 我打算在输入框中执行一些Jquery验证。 If this is invalid I want to add the error class to the div 如果这是无效的,我想将错误类添加到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;

I've tried to target the parent but see that this div is further up the parent heirachy. 我曾尝试定位父级,但看到该div距父级父级更高。 so tried to select up the heirachy with more parent tags, but think I am straying well off course from understanding the correct way to target the div. 因此尝试选择带有更多父标签的heirachy,但认为我偏离了正确的定位div的目标。

I suggest using .closest() : 我建议使用.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. 描述 :对于集合中的每个元素,通过测试元素本身并遍历DOM树中的祖先,获得与选择器匹配的第一个元素。

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;

如果您需要查找树,请使用.parents()方法并将其传递给包含div的类,即: .parents('.row')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM