【发布时间】:2015-04-05 05:23:04
【问题描述】:
我有 10 个不同的复选框,每个复选框都有其唯一 ID - 按顺序排列,例如:cbox1、cbox2 等。每个复选框都有一个关联的“tinybox”div,其中包含一个图像,每个图像都有一个ID 也是按顺序排列的,例如tinypic1、tinypic2 等。我正在尝试编写一个 jQuery 脚本,以便当用户单击任何复选框时,它将是 .show() 或 .hide()关联的 tinypic。
例如,假设用户点击了 id="cbox3" 的第三个复选框,脚本应该识别这是 cbox THREE,因此显示或隐藏“tinypic3”。每个复选框都有一个唯一的 ID,但具有相同的类(称为 cboxes)。
当点击任何 cbox 时,此 jQuery 脚本成功使用该类运行,但我如何让它显示/隐藏关联的 TINYPIC 而不是显示/隐藏 cbox 本身?
<script type="text/javascript">
$(document).ready(function() {
$('.cboxes').click(function() {
if ($(this).prop('checked')) {
$(this).next().show(); // This should show the associated tinypic with the same number as the cbox that was clicked.
}
else {
$(this).next().hide(); // This should hide the associated tinypic with the same number as the cbox that was clicked.
}
});
});
</script>
我尝试将$(this).next().show(); 替换为$("[id^='tinypic']").show(); 或$('input:checkbox[id^="tinypic_"]'),但它不起作用。我显然不明白其中的逻辑。
任何帮助都是巨大的!非常感谢:)
这是 cbox2 的示例复选框:
<li>
<input id="cbox2" type="checkbox" name="cbox2" class="cboxes" />
<label for="cbox2">Show</label>
<div class="tinybox">
<img src="http://www.example.com/img/temp.jpg" alt="tinypic2" id="tinypic2" style="display:none;">
</div>
</li>
【问题讨论】:
标签: javascript jquery html checkbox