我正在尝试学习并创建一个$("#answer")
的jquery,并找到里面的所有复选框并检查。例如,如果选中#a1
内的复选框,则隐藏其他div(a2,a3,a4)或其他消息。如果我取消选中#a1
所有div将再次出现。
请告诉我代码。
<div id="answer">
<div id="a1">A.<input type="checkbox" name="a1" onclick="cbox()" ></input></div>
<div id="a2">B. <input type="checkbox" name="a2"onclick="cbox()"></input></div>
<div id="a3">C. <input type="checkbox" name="a3"onclick="cbox()"></input></div>
<div id="a4">D. <input type="checkbox" name="a4"onclick="cbox()"></input></div>
</div>
function cbox() {
if (this checkbox is checked) {
target other div inside (#answer) and add .hide()
}
}
2)无论如何都要添加一个触发器,我不需要使用onlick =&#34; cbox&#34; ?
TQ
答案 0 :(得分:1)
最好使用 .click() 而不是内联javascript onclick
。
但是,您应该对input
元素使用 .change() 事件而不是点击:
$('input[type="checkbox"]').change(function() {
$(this).parent().siblings('div').toggle(!this.checked);
});
<强> Fiddle Demo 强>
答案 1 :(得分:1)
$('input[type="checkbox"]').change(function() {
$(this).parent('div').siblings('div').toggle(!this.checked);
});
<强> DEMO 强>
答案 2 :(得分:0)
试试这个:
$("#answer input").change(function () {
if ($(this).is(":checked")) {
$("#answer input").not(this).each(function () {
$(this).parent().css("display", "none");
})
} else {
$("#answer input").not(this).each(function () {
$(this).parent().css("display", "block");
})
}
});