Javascript 将切换按钮替换为复选框,但不起作用

Javascript 将切换按钮替换为复选框,但不起作用,javascript,jquery,html,checkbox,Javascript,Jquery,Html,Checkbox,我用一个复选框替换了jQuery切换代码上的按钮,但无法使其工作 这是我试图用复选框替换按钮的HTML文件 index.html <p> hi </p> <!--<button>Press me</button>--> <div class="onoffswitch"> <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox"

我用一个复选框替换了jQuery切换代码上的按钮,但无法使其工作

这是我试图用复选框替换按钮的HTML文件

index.html

<p> hi </p>
<!--<button>Press me</button>-->
<div class="onoffswitch">
    <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>
    <label class="onoffswitch-label" for="myonoffswitch"></label>
</div>

这里怎么了?

$(函数(){
$('#myonoffswitch')。单击(函数(){
/*如果只需要隐藏和显示,请使用切换*/
//$(“p”).toggle();
/*如果您想知道复选框的当前状态,请使用以下代码*/
如果($(this).is(':checked')){
$(“p”).show();
}否则{
$(“p”).hide();
}
})
});


实际上,您根本没有使用复选框类。这就是它不起作用的原因

按如下方式操作:-

改变-

$('#myonoffswitch.onoffswitch').is(":checked"), function() {

一切都会好起来的

工作示例:-


注意:-您可以使用:-
$('.onoffswitch复选框').change(function(){
也可以(by@NikhilNanjappa)

但是,您希望输出是什么?您写了问题,但是在回答中期望得到什么?@AlivetoDie,Html上的,以及$('button')。on('click',function()脚本上的注释已被删除。这些是原始代码,我正在尝试使用复选框使其工作。@DeepakYadav,hide and show ontoggle@Mecom-在
$(“#myonoffswitch.onoffswitch”中)
onoffswitch
不存在。在该元素上使用的类是
onoffswitch checkbox
。因此该函数甚至不会被调用。
onoffswitch
在其父元素上使用,而不是在该元素上使用element@NikhilNanjappa,我试了你说的,但没用。你能在我贴的小提琴上给我看看吗?我替换了整个脚本,但它没有切换。@如果要查找,请检查代码段this@Mecom很高兴为您提供帮助:):)只需添加,您还可以使用
$('.onoffswitch复选框').change(function(){
@AlivetoDie-
更改
事件。只是OP@NikhilNanjappa很好。添加到答案中。谢谢。看到时错过了
$('#myonoffswitch.onoffswitch').is(":checked"), function() {
$('.onoffswitch-checkbox').click(function() {