[英]jQuery. Check onload if checkbox is checked and add css to div
[英]javascript check if checkbox is not checked not hiding div onload
我正在檢查頁面上是否選中了一個復選框,如果沒有選中,我想隱藏一個div。 我不確定這是否是由於我的div沒有內聯元素引起的,但是我仍然無法使用該方法。 我還使用Cookie來記住為每個用戶選擇的選項。 Cookies部分工作正常,只是隱藏了div而不起作用。 這是代碼:
function setCookie(c_name,value,expiredays) {
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate)
}
function getCookie(c_name) {
if (document.cookie.length>0) {
c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1) {
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return null
}
function checkCookie(){
document.getElementById('john').checked = getCookie('calOption1')==1? true : false;
document.getElementById('steve').checked = getCookie('calOption2')==1? true : false;
$(document).ready(function() {
if ($('#john').is(':checked')) {
$('.ms-acal-color2').css('display', 'block');
}else{
$('.ms-acal-color2').css('display', 'none');
}
});
$('#john').change(function() {
if (this.checked) { //if ($(this).is(':checked')) {
$('.ms-acal-color2').css('display', 'block');
} else {
$('.ms-acal-color2').css('display', 'none');
};
});
}
function set_check(){
setCookie('calOption1', document.getElementById('john').checked? 1 : 0, 100);
setCookie('calOption2', document.getElementById('steve').checked? 1 : 0, 100);
}
編輯:這是HTML代碼
<div style="float: left;">
<div id="myForm">
<input type="checkbox" onchange="set_check();" id="john"/>
<label>Show John</label>
<input type="checkbox" onchange="set_check();" id="steve"/>
<label>Show Steve</label>
</div>
</div>
您的代碼是一團糟:)您不應該將JavaScript sintax與jquery結合使用,僅使用其中之一...
您還使某些事情感到困惑,您在函數內添加了文檔就緒偵聽器,其他事件偵聽器也...
我清理了您的代碼,在這里查看結果: http : //jsfiddle.net/Hezrm/
要查看它與Cookie配合使用,請訪問: http : //jsfiddle.net/promatik/Hezrm/show
以下是Javascript中的更改:
// In the Document Ready listener you are going to check cookies and
// hide "everyone" that is not checked
$(document).ready(function() {
checkCookie();
$(".person:not(:checked)").next().hide();
});
// This is a change eventlistener that will hide or show people at runtime
$('#john, #steve').change(function() {
if( $(this).is(':checked') ) $(this).next().show();
else $(this).next().hide();
set_check(); // And save changes to cookies
});
function checkCookie(){
$('#john').attr("checked", getCookie('calOption1') == 1 ? true : false);
$('#steve').attr("checked", getCookie('calOption2') == 1 ? true : false);
}
function set_check(){
setCookie('calOption1', $('#john').is(':checked')? 1 : 0, 100);
setCookie('calOption2', $('#steve').is(':checked')? 1 : 0, 100);
}
我還添加了一個.person
類,以使其更容易隱藏或顯示復選框:
<input type="checkbox" id="john" class="person"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.