繁体   English   中英

jQuery查找特定输入的父级并应用类

[英]jquery find parents of specific inputs and apply class

我有一个内部带有复选框的选择div,我正尝试使用自举按钮和jQuery设置样式。 每个input checkbox采用php "checked"属性。 所以我需要的是:

  • 找到所有“已检查”的inputs ,转到parent标签,最终addClass active

我的html(在php foreach循环中)

<?php
global $wpdb;
$ss = "select * from ".$wpdb->prefix."project_email_alerts where uid='$uid'";
$rr = $wpdb->get_results($ss);
$terms = get_terms( 'project_cat', 'parent=0&orderby=name&hide_empty=0' );
foreach($terms as $term):
    $chk = (KleeiaDev_check_list_emails($term->term_id, $rr) == true ? "checked='checked'" : "");?>
    <div data-toggle="buttons" class="btn-group bizmoduleselect">
        <label id="b-<?php echo $term->term_id; ?>" class="btn btn-default">
            <div class="bizcontent">
                <input id="a-<?php echo $term->term_id ?>" type="checkbox" name="email_cats[]" <?php echo $chk ?> value="<?php echo $term->term_id ?>" />
                <span class="glyphicon glyphicon-ok glyphicon-lg"></span>
                <h5><?php echo $term->name ?></h5>
            </div>
        </label>
    </div>
<?php endforeach; ?>

我已经尝试过使用jQuery来搜索其他类似问题,但均未成功:

if($('input').is(':checked')){
   jQuery(this).parent('label').addClass('active');
}

我已经尝试使用.each了,但是对此并不确定。

您可以使用

$('input[type=checkbox]:checked').parents('label').addClass('active');

  $('input[type=checkbox]:checked').parents('label').addClass('active'); 
 .active{ color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <label > <input type='checkbox' checked='true'> Check me <label> </div> <div> <label> <input type='checkbox'> Check me <label> </div> 

在客户端添加类也许很重要,但是在服务器端也可以这样做:

$chk = (KleeiaDev_check_list_emails($term->term_id, $rr) == true ? "checked='checked'" : "");?>
<label id="b-<?php echo $term->term_id; ?>" class="btn btn-default <?=!empty($chk) 'active' : ''?>">

暂无
暂无

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

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