繁体   English   中英

当另一个复选框被激活时启用点击事件

[英]Enable click event when another checkbox is cheched

我需要一个执行以下操作的jQuery函数:例如,当复选checkbox1时,当我单击其他一些元素(id以element-开头)时,我可以在控制台中打印这些元素的id ,如下所示:

$('#checkbox1').click(function() {
    if ($(this).is(':checked')) {
        $(document).on('click','[id^=element-]', function(e) {
            console.log(this.id);
        });
    } else {}
});

我测试了这个例子并且没有用。 我不知道我什么时候错了。

最简单的方法是颠倒你的逻辑。 也就是说,将click处理程序放在所需的元素上,并在其中检查复选框的状态。 试试这个:

 $(document).on('click', '[id^="element-"]', function(e) { if ($('#checkbox1').is(':checked')) console.log(this.id); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label> <input type="checkbox" id="checkbox1" /> Check me! </label> <div> <button id="element-foo">Foo</button> <button id="element-bar">Bar</button> </div> 

我测试了它,这对你有用

 $("input[id^=d]").on("click", function() { var id = $(this).prop("id"); if ($("#c1").is(":checked")) { console.log(id); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Dogs <input id="c1" type="checkbox" /> Cats <input id="d1" type="checkbox" /> Zebras <input id="d2" type="checkbox" /> Rhinos <input id="e1" type="checkbox" /> 

暂无
暂无

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

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