简体   繁体   English

如何使用jQuery查找最接近元素的属性?

[英]How do find the attribute of the closest element using jQuery?

I have the following markup: 我有以下标记:

<div class="span6">
             <form> 
                <fieldset>
                    <label>Name:</label>
                    <input type="text" class="success field span6" placeholder="Name" name="name" id="name"> <i id="name" class="check"></i>
                    <label>Email:</label>
                    <input type="text" class="field span6" placeholder="Email" name="email" id="email" > <i id="email" class="check"></i>
                    <label>Message:</label>
                    <i id="message" class="check"></i><textarea class="field span9" rows="8" placeholder="Message" name="message" id="message"></textarea>
                    <label class="checkbox">
                    </label>
                    <button type="submit" class="btn disabled">Send Message</button>
                </fieldset>
            </form>
        </div>
    </div>

And the following jQuery: 和下面的jQuery:

    $('input,textarea').keyup(function(){
       console.log($(this).closest(".check").attr("id"));
    });

The value I get returned is undefined. 我返回的值是不确定的。 How do I find the value of the id attribute for an element of the class '.check' when the tag is before or after the input (ie if all the tags were after I would use $().next())? 当标签在输入之前或之后(即,如果所有标签都在我将使用$()。next()之后)时,如何查找类'.check'的元素的id属性值?

Try 尝试

var check = $(this).next(".check");
if(!check.length){
    check = $(this).prev(".check");
}
console.log(check .attr("id"));

Demo: Fiddle 演示: 小提琴

use next if input and prev if textarea....; 如果输入则使用next如果是textarea则使用prev try this 尝试这个

var checkID='';
 $('input,textarea').keyup(function(){
   if($(this).is("input")){
     checkID=$(this).next(".check").attr("id");
   }else{
     checkID=$(this).prev(".check").attr("id");
   }
      console.log(checkID);
});

First your html is incorrect, remember that the attribute ID must be unique. 首先,您的html不正确,请记住属性ID必须是唯一的。

Then, you can go to the parent (ie the form tag) and find the child you want, like this: 然后,您可以转到父项(即form标签)并找到所需的子项,如下所示:

$('input,textarea').keyup(function(){
   console.log($(this).parents("form").find(".check").attr("id"));
});

try this 尝试这个

$('input,textarea').keyup(function(){
       console.log($(this).find().closest(".check").attr("id"));
    });

You are using closest() wrong. 您使用close()错误。 Closest fetches the closest parent. 最接近的将获取最接近的父级。 Best approuch is going back to its parent and fetch the child. 最好的approuch回到其父级并获取该子级。 Find and first will both work in this case 在这种情况下,查找和首先都可以使用

console.log($(this).parent().first(".check").attr("id"));

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

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