[当前,下面的HTML代码仅在您单击输入时(即中心开关)才切换。我需要在单击标签时进行切换(即“是”或“否”)。如何做到这一点?
<div>
<span class="frm_off_label frm_switch_opt">No</span>
<label class="frm_switch">
<input type="checkbox" name="2002" id="field_2002" value="Yes" checked="checked"
data-off="No" data-sectionid="2002" data-frmval="Yes" placeholder="Yes">
<span class="frm_slider"></span>
</label>
<span class="frm_on_label frm_switch_opt">Yes</span>
</div>
单击是或否的方式与单击输入相同吗?
使用label
标签而不是span
标签并将id
属性设置为指向input#id
。
<div>
<label for="field_2002" class="frm_off_label frm_switch_opt">No</span>
<label class="frm_switch">
<input type="checkbox" name="2002" id="field_2002" value="Yes" checked="checked"
data-off="No" data-sectionid="2002" data-frmval="Yes" placeholder="Yes">
<span class="frm_slider"></span>
</label>
<label for="field_2002" class="frm_on_label frm_switch_opt">Yes</span>
</div>
您可以通过设置输入的检查状态来实现-->
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <label for="field_2002" class="frm_off_label frm_switch_opt">No</label> <input type="checkbox" name="2002" id="field_2002" value="Yes" checked="checked" data-off="No" data-sectionid="2002" data-frmval="Yes" placeholder="Yes"> <label for="field_2002" class="frm_on_label frm_switch_opt">Yes</label> </div>
JS(带有jquery)
<div> <span class="frm_off_label frm_switch_opt">No</span> <label class="frm_switch"> <input type="checkbox" name="2002" id="field_2002" value="Yes" checked="checked" data-off="No" data-sectionid="2002" data-frmval="Yes" placeholder="Yes"> <span class="frm_slider"></span> </label> <span class="frm_on_label frm_switch_opt">Yes</span> </div>
CSS(optioanl)
$('.frm_off_label').on('click', function(){ $(this).next('label').find("input")[0].checked = false; }); $('.frm_on_label').on('click', function(){ $(this).prev('label').find("input")[0].checked = true; });
您可以在jsfiddle上看到它的作用
.frm_switch_opt{
cursor:pointer;
}