我的复选框有问题。我有一系列的照片。每张照片都有一个复选框。如果选中照片的复选框,则会使用 .show() 显示与照片关联的 div。
效果很好,我可以提交表单。但是,如果我按浏览器上的“后退”返回到照片集,复选框仍处于选中状态,但与其关联的 div 不再可见。
我需要做什么才能确保检查的照片即使在“返回”页面时仍然具有可见的 div?
$(document).ready(function () {
$(':checkbox').change(function() {
var dataID = $(this).attr("id");
if($(this).is(':checked')) {
$("#content"+dataID).show();
}
else {
$("#content"+dataID).hide();
}
});
});
形式是这样的:
<form>
<input name="box1" id="box1" type="checkbox" />
<input name="box2" id="box2" type="checkbox" />
<input name="box3" id="box3" type="checkbox" />
...
</form>
最佳答案
尝试在页面加载时显示选中的 div 的图像,即类似:
$(document).ready(function () {
$(':checkbox').change(function() {
// ... your code ...
});
$(':checkbox').each(function() {
var dataID = $(this).attr("id");
if($(this).is(':checked')) {
$("#content"+dataID).show();
}
else {
$("#content"+dataID).hide();
}
});
});
简洁版本
$(document).ready(function () {
$(':checkbox').change(function() { checkImage($(this)); });
$(':checkbox').each(function() { checkImage($(this)); });
});
function checkImage(_checkBox) {
var dataID = _checkBox.attr("id");
if(_checkBox.is(':checked')) {
$("#content"+dataID).show();
}
else {
$("#content"+dataID).hide();
}
}
关于在浏览器上按 "back"后,Javascript 切换复选框不再可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11389260/