2015-10-22 162 views
1

我有4个单选按钮隐藏在每个div内的每个图像下。单选按钮组jquery点击事件

<div class="temp-inner" id="someid"> 
     <?php while($row = mysql_fetch_array($res)){?> 
      <div data-id="<?=$row['id'];?>" class="hand temp-selector"> 
       <input type="radio" name="templates_id" class="templates_id" value="<?=$row['id'];?>" /> 
       <label class="temp-type" style="background-image:url(<?=$row['src'];?>)"></label> 
      </div> 
     <? } ?> 
    </div> 

我需要单选按钮下的图像检查=,所以我决定创建的onClick功能

$(".hand").on("click", function() { 
    $(this).children("input:radio[name=templates_id]").attr('checked',true); 
} 

这部分运行完美。现在我想添加新的类,如果单选按钮被选中。我认为我可以使用if - else语句,但它不起作用。

$(".hand").on("click", function() { 
    $(this).children("input:radio[name=templates_id]").attr('checked',true); 

    if($("input:radio[name=templates_id]").is(":checked")) { 
     $(".hand").addClass("active"); 
    } else { 
     $(".hand").removeClass("active"); 
    } 
}; 

我该如何正确书写它? Thx很多,最好的问候!

回答

1

下面的代码将检查收音机的股利点击,去除手类每格主动类并添加活动类到div点击。

$(document).on('click', '.hand', function() { 
    $(this).children("input:radio[name=templates_id]").prop('checked', true); 
    $(".hand").removeClass("active"); 
    $(this).closest("div.hand").addClass("active"); 
}); 
+0

当然,我可以toggleClass ..但我需要删除它,如果电台 - 未选中。 ('click',function(){ $(this).children(“input:radio [name = templates_id]”)。attr('checked', true); $(this).toggleClass(“active”); }); '''在这种情况下 - 它只是将类添加到所有被点击的div中,我只需要一个选中的广播..并且div.active与它 – Yevgen

+0

如何取消选中广播?只有检查它的代码。我编辑了我的答案和代码来取消收音机。 – krlzlx

+0

我以为我不需要取消收音机..它只是检查下一个 – Yevgen

1

你可以使用length属性,尝试:

$(".hand").on("click", function() { 
    $(this).children("input:radio[name=templates_id]").attr('checked',true); 

    if($("input:radio[name=templates_id]").length > 0) { 
     $(".hand").addClass("active"); 
    } else { 
     $(".hand").removeClass("active"); 
    } 
};