简体   繁体   English

jQuery-如何根据孩子的属性选择父母?

[英]jQuery - How do you select a parent based on the attribute of a child?

How do you select a parent based on the attribute of a child? 如何根据孩子的属性选择父母?

I want to select a div: 我想选择一个div:

that has a child with the radio:checked 有收音机的孩子:已检查

<div> <input id="1" type="radio"/> </div>
<div> <input id="2" type="radio"/> </div>

for example. 例如。

$('div radio:checked').click(function(){
     $(*** div parent based on radio:checked ***).css({'background':'#F00'});
});

closest() 最近()

$('div radio:checked').click(function(){
    $(this).closest('div').css({'background':'#F00'});
});

if you want the nearest 'parent' div, even if it is several levels up. 如果您想要最近的“父级” div,即使它是多个级别的。

parent() 父()

$('div radio:checked').click(function(){
    $(this).parent('div').css({'background':'#F00'});
});

if you want the direct parent 如果您想要直接父母

Interestingly, you can do a sort of reverse lookup selector with :has like 有趣的是,您可以使用:has进行某种反向查找选择器

$('div:has(radio:checked)').click(function(){
    $(this).css({'background':'#F00'});
});

try: 尝试:

$('div radio:checked').click(function(){
 $(this).parent().css({'background':'#F00'});
});

UPDATE: 更新:

the 'div radio:checked' do not work in your code, you can use: 'div radio:checked'在您的代码中不起作用,您可以使用:

$('div input[type=radio]').click(function () {
 $(this).parent().css({'background': '#F00'});
});

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

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