单击或选择行上的任意位置以选中复选框并突出显示它?

时间:2017-02-01 06:33:22

标签: javascript php jquery

enter image description here您好我正在使用Java脚本生成一个带切换复选框的表我想突出显示是否正在选择或点击我如何修改我的代码?

function draw_equipment($equipment)
{
    $equipment_name = $equipment['img_link'];
    echo "<div style='text-align:left;width:120%'>";
    echo "<input type='checkbox' class='toggleCheckbox'>";
    echo "<img src='img/$equipment_name' alt='$equipment_name' width='120px'/><br/>";
    echo $equipment['equip_type'];
}

1 个答案:

答案 0 :(得分:2)

在复选框上使用toggleClass并将其包装在标签中以允许单击图像。

我也会在加载时执行更改,以防复选框已设置为在服务器上检查或重新加载

&#13;
&#13;
$(function() {
    $(".toggleCheckbox").on("change",function() {
      $(this).closest("div").toggleClass("checked",this.checked);
    }).change(); // run at load too
});
&#13;
.checked { background-color:pink }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div style='text-align:left;width:120%'><label><input type='checkbox' class='toggleCheckbox'><img src='https://logos.tlecdn.net/100x30/m_1203_marantz_7.png' alt='$equipment_name' width='120px'/></label></div>
<hr/>
<div style='text-align:left;width:120%'><label><input checked type='checkbox' class='toggleCheckbox'><img src='https://resources.sport-tiedje.com/bilder/ciclosport/ciclosport_t.gif' alt='$equipment_name' width='120px'/></label></div>
&#13;
&#13;
&#13;

如果你需要点击WHOLE div来突出显示,你需要为div添加一个事件处理程序,但是你需要stopPropagation

&#13;
&#13;
$(function() {
    $("div").has(".toggleCheckbox").on("click",function() {
      $(this).find(".toggleCheckbox").click();
    });
    $(".toggleCheckbox").on("click",function(e) {
      e.stopPropagation(); // this should not bubble to the div
    })
    $(".toggleCheckbox").on("change",function(e) {
      $(this).closest("div").toggleClass("checked",this.checked);
    }).change(); // run at load too
});
&#13;
div { background-color: #778899}
.checked { background-color:green }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div style='text-align:left;width:120%'><label><input type='checkbox' class='toggleCheckbox'><img src='https://logos.tlecdn.net/100x30/m_1203_marantz_7.png' alt='$equipment_name' width='120px'/></label></div>
<hr/>
<div style='text-align:left;width:120%'><label><input checked type='checkbox' class='toggleCheckbox'><img src='https://resources.sport-tiedje.com/bilder/ciclosport/ciclosport_t.gif' alt='$equipment_name' width='120px'/></label></div>
&#13;
&#13;
&#13;