当另一个复选框被选中时启用单击事件

3
我需要一个jQuery函数,能够完成以下任务:例如,当选中checkbox1时,当我点击其他一些元素(其id以element-开头)时,我可以将这些元素的id打印到控制台上,如下所示:
$('#checkbox1').click(function() {
    if ($(this).is(':checked')) {
        $(document).on('click','[id^=element-]', function(e) {
            console.log(this.id);
        });
    } else {}
});

我测试了这个例子,它没有工作。我不知道我错在哪里。

1
console.log($(this).attr('id')) - sTx
除了@sTx的评论之外,确保你的代码被包含在$(document).ready(function() {...})中。 - Tricky12
看起来它也适用于 this.id - 没想到 :) - sTx
你应该考虑使用类(classes)而不是搜索以特定字符串开头的 id。这样会更快。 - Heretic Monkey
@sTx 是的。this 是引发事件的 DOM 元素的引用。因此,您可以调用该对象的任何属性,例如 iddatasetclassList 等。 - Rory McCrossan
2个回答

4
最简单的方法是反转你的逻辑。也就是说,在所需元素上放置点击处理程序,并在其中检查复选框的状态。请尝试以下代码:

$(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>


0
我测试过了,这对您来说是可行的。

$("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" />


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接