2010-08-10 120 views
1

我正在製作一個簡單的jQuery腳本,它將允許您通過單擊按鈕來更改某些內容。我的問題是,如果我更改了值(選中),然後單擊提交按鈕,它會將其識別爲默認值。如果您在默認情況下執行此操作,則會將其設置爲關閉,因此如果您將其選中(打開),然後單擊提交按鈕,它將是默認(關閉)命令。我知道這是因爲我使用本地存儲來保存設置。因此,如果您檢查它,刷新,然後單擊提交,它將執行適當的操作。按鈕點擊變量未更新?

這裏是我的jQuery:

$(document).ready(function(){ 
var test='false' 

if (localStorage.getItem('simpSet')){ 
element = document.getElementById('simplify'); 
var test=localStorage.getItem('simpSet'); 

if(test == 'true'){ 
element.setAttribute('checked'); 
} 

console.log(test); 
} 

$('#simplify').live('click', function(){ 

if ($('#simplify').is(':checked')){ 
var test='true' 
console.log(test); 

}else{ 
var test='false' 
console.log(test); 
} 
localStorage.setItem('simpSet', test); 

}); 

$('#button').live('click', function(){ 
console.log(test); 

if(test == 'true'){ 
console.log('isTrue'); 
$('#test').css('background', 'blue'); 
return false; 
}else{ 
$('#test').fadeOut('slow'); 
return false; 
} 

}); 

}); 

和我簡單的標記

<span id='simcont'>Simplify<input type='checkbox' id='simplify'></span> 

<input type="submit" val='Go' id='button'> 
<div id='test'>Testing simplifier</div> 

任何想法有什麼不對?

例子:http://kod.singaming.net/simplify/

默認的文本會消失,如果你檢查它,它應該把文字背景爲藍色。這不能正常工作,所以它會褪色,但如果你檢查它,刷新,然後提交它會將背景變成藍色。

回答

1

我會改變

var test = 'true'; 

test = 'true'; 

在複選框活動區域。該變量不能在點擊事件功能之外訪問。

編輯:同樣的事情取消選中。刪除'var'

+0

謝謝!那樣做了。 – MoDFoX 2010-08-10 00:31:08