我有一个按钮,我想执行以下操作
我找到了两个完全符合我需要的参考资料,但我不知道如何将这两个解决方案放在一起。 This 和 this
HTML 代码
<div id="billing">
<input type="checkbox" id="billing-checkbox" checked>
<input type="button" value="Hello Javascript!">
</div>
Javascript 代码
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('billing-checkbox').onchange = toggleBilling;
}, false);
function toggleBilling() {
var billingItems = document.querySelectorAll('#billing input[type="button"]');
for (var i = 0; i < billingItems.length; i++) {
billingItems[i].disabled = !billingItems[i].disabled;
}
}
$(function(){
var test = localStorage.input === 'true'? true: false;
$('input').prop('checked', test || false);
});
$('input').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
非常感谢!
答案 0 :(得分:1)
这将在代码段中出现脚本错误,可能是因为它是一个沙箱并且不允许使用 localStorage。但这已经过测试并且有效。有关解释,请参阅代码中的注释。您可以打开或关闭复选框,当您刷新页面时,它会“记住”它的状态
$(document).ready(function() {
// first thing is to set the checkbox based on the localStorage key that we may have set in the past
$('#billing-checkbox').prop('checked', localStorage.getItem('buttonDisabled') !== "disabled");
// then we run our toggle billing
toggleBilling()
// we set up our change handler.
$('#billing-checkbox').on('change', toggleBilling);
});
function toggleBilling(e) {
// we set the disabled based on the check button status
$('#billing input[type="button"]').attr('disabled', !$('#billing-checkbox').prop('checked'))
// we set the localStorage based on the button disabled
localStorage.setItem('buttonDisabled', $('#billing input[type="button"]').attr('disabled'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="billing">
<input type="checkbox" id="billing-checkbox" checked>
<input type="button" value="Hello Javascript!">
</div>