我正在为Phonegap应用程序(jQuery Mobile)开发一个简单的登录屏幕。
一切正常,用户甚至可以通过单击复选框保存登录数据(我使用localStorage。)现在,当用户点击Logout时,我想将用户重定向到登录屏幕,并选中未选中的复选框 - 按钮。重定向工作正常,密码被删除。唯一的问题是复选框,它一直被检查,即使我告诉它不被选中。
这是我的代码:
HTML
...
<form id="login">
<input type="text" placeholder="Username" id="usr" /><br />
<input type="password" placeholder="Password" id="pwd" /><br />
<input type="checkbox" name="checkbox-1" id="checkbox-1" class="custom" />
<label for="checkbox-1">Stay logged in</label>
<a data-role="button" data-transition="none" id="logindata" onclick="LogIn()">Login</a>
</form>
...
的javascript
//checking if there is already a saved password. if yes, setting values
function checkStorage() {
if ( localStorage["pw"] != null){
document.getElementById("usr").value = localStorage["name"];
document.getElementById("pwd").value = localStorage["pw"];
$("#checkbox-1").prop("checked", true);
}
}
function LogIn() {
var usr = document.getElementById('usr').value;
var pwd = document.getElementById('pwd').value;
//always saving the name
localStorage["name"] = usr;
//if checkbox checked, save the password. if not, delete saved password
if ( $("#checkbox-1").is(":checked") ) {
localStorage["pw"] = pwd;
} else {
if (localStorage["pw"] != null){
localStorage.removeItem("pw");
}
}
$.ajax({
url: 'https://myurl',
async: false,
username: usr,
password: pwd,
success: function () {
$.mobile.changePage("#success");
},
error: function(){
alert("Please enter correct username and password!");
}
});
}
function LogOut() {
var usr = "";
var pwd = "";
$.mobile.changePage("#index");
document.getElementById("usr").value = localStorage["name"];
document.getElementById("pwd").value = "";
localStorage.removeItem("pw");
//This code is not working?
$("#checkbox-1").prop("checked", false);
}
当我使用此代码时,我想对密码进行编码,但是现在我只想让它运行起来。 ;)
我希望,有人可以帮助我吗?
修改
我终于发现了,发生了什么。我在这个登录表单中使用jQuery Mobile,并且必须刷新复选框!所以下面的代码现在适用于我:
$("#checkbox-1").removeProp("checked").checkboxradio("refresh");
答案 0 :(得分:0)
如果你做了
removeProp("checked")
而不是
prop("checked", false)
我认为你应该取得更大的成功。
修改强>
只是一个想法,你的登录表单是否在带有id索引的元素中?如果是这样,更改页面不需要低于localstorage.removeitem?
答案 1 :(得分:0)
你可以做到
$(document).ready(function(){
if($("#checkbox-1").is(':checked')){
$('#checkbox-1').removeAttr('checked');
}
})