我有 10 个不同的复选框,每个都有其唯一的 ID - 按顺序排列,例如:cbox1
、cbox2
等。每个复选框都有一个关联的“tinybox”div其中包含一个图像,并且每个图像都有一个按顺序排列的 ID,例如 tinypic1
、tinypic2
等。我正在尝试编写一个 jQuery 脚本,这样当用户点击任何复选框,然后它将 .show()
或 .hide()
与 tinypic 相关联。
例如,假设用户点击了 id="cbox3"的第三个复选框,脚本应该识别这是 cbox THREE,因此显示或隐藏“tinypic3”。每个复选框都有一个唯一的 ID,但具有相同的类(称为 cboxes)。
此 jQuery 脚本成功使用该类在单击任何 cbox 时运行,但如何让它显示/隐藏关联的 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>
最佳答案
这是一个工作代码 jsfiddle
$(document).ready(function() {
$('.cboxes').change(function() {
var image = $(this).siblings(".tinybox").find("img");
if ($(this).prop('checked')) {
image.show(); // This should show the associated tinypic with the same number as the cbox that was clicked.
}
else {
image.hide(); // This should hide the associated tinypic with the same number as the cbox that was clicked.
}
});
});
所以首先我们应该使用 change
事件而不是 click 来处理点击和任何变化。
其次我们不应该只操作next item而是通过类查找sibling如果html改变了我们不需要改变JS代码。
最后,当我们找到这个元素时,我们应该在其中搜索图像以根据复选框选中状态显示或隐藏它,在这里我们甚至可以改进我的代码
这是 jsfillde 的更新版本
$(document).ready(function() {
$('.cboxes').change(function() {
var image = $(this).siblings(".tinybox").find("img");
image.toggle($(this).prop('checked'));
});
});
关于javascript - 如何根据单击的复选框显示/隐藏特定图像(单击 cbox3 应打开 tinypic3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29447112/