简体   繁体   English

jQuery遍历父标签

[英]jQuery Traversing For Parent Label

I'm having trouble traversing to find a certain element. 我在遍历中找不到特定元素时遇到麻烦。 I have the following html: 我有以下html:

<div class="form-group">
        <label for="example" class="col-sm-2">Example</label>
        <div class="col-sm-10">
            <input type="text" name="example" class="form-control">
        </div>
    </div>

I can select the input example, and I would like to select the contents of label, so it would be "Example". 我可以选择输入示例,而我想选择标签的内容,因此它将是“示例”。 I can't do parent().parent() because since I'm using bootstrap, if I had a radio or a select, the tree would be different. 我不能做parent()。parent(),因为由于我使用的是引导程序,所以如果我有收音机或选择器,那棵树会有所不同。 Any suggestions? 有什么建议么?

You can target it with closest() 您可以使用closest()

$('.form-control').closest('.form-group').find('label:eq(0)').text()

OR 要么

$('.form-control').closest('div').prev('label').text()

OR 要么

$('.form-control').closest('div').siblings('label').text()

Try jQuery's .closest(); 试试jQuery的.closest();

More info on their documentation page which can be found here: .closest() 有关其文档页面的更多信息,请参见: .closest()

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

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