如何知道元素是否在其类中包含另一个元素

时间:2013-09-20 05:21:00

标签: javascript jquery html

<html>
<head>
<script>
function A(){
    $('input[name="B[]"]').each(function() { 
        if(('$(this) .BtnSet .Child input:text[name="A[]"]').length){
         //yes the Child class is inside JRow class and has textboxes with name A[]
        }
    });
    return false;
}
</script>
</head>
<body>
<form onsubmit="return A()">
    <div class="row JRow">
     <input type="text" name="B[]"></input>
     <input type="text" name="B[]"></input>
        <div class="BtnSet">
            <div class="Child">
                <input type="text" name="A[]"></input>
                <input type="text" name="A[]"></input>
            </div>
        </div>
    </div>
    <input type="submit" value="Submit"></input>
</form>
</body>
</html>

我需要检查B []是否有BtnSet类。在它里面,是否有一个Child类,里面是否有像A []这样的子元素。我准确地完成了吗? 但问题是在这种情况下,当我打印警报('$(this).BtnSet .Child输入:text [name =“A []”]')。length)长度总是为45.请解释我原因是什么?它没有给出2的正确长度吗?

3 个答案:

答案 0 :(得分:2)

$(this).find("*[class='BtnSet']").length;

你得到字符串长度,$(this)应该在外面,就像@CoursesWeb指出这些不是输入元素的子节点,其名称= b []但是兄弟姐妹,你将不得不使用{ {1}}为此!

siblings

答案 1 :(得分:0)

BtnSet不是B []的内部,但是row jRow中的孩子,就像B []。

文字输入标签没有子项目。

答案 2 :(得分:0)

我认为数字45是您显然不需要的字符串 $(this) .BtnSet .Child input:text[name="A[]"]的长度。你需要的是两个输入元素的长度,它在div.BtnSet范围内。所以这应该有用

 $(this).siblings("div.BtnSet").first().find("input[name='A[]']").length;