我有一个包含 5 个 html 页面的 localStrg.js 文件,并且页面内存在某些页面中不存在的元素。我想验证这样的元素是否存在,以及它是否确实获取了它的值并将其用作默认值/我在 js 文件中有这个:
function initialize() {
// Test to see if we support the Storage API
var SupportsLocal = (('localStorage' in window) && window['localStorage'] !== null);
var SupportsSession = (('sessionStorage' in window) && window['sessionStorage'] !== null);
// if either one is not supported, then bail on the demo
if (!SupportsLocal || !SupportsSession) {
document.getElementById('infoform').innerHTML = "<p>Sorry, this browser does not support the W3C Storage API.</p>";
return;
}
// if the localStorage object has some content, restore it
if (window.localStorage.length != 0) {
for(i=0;i<window.localStorage.length;i++){
if(document.getElementById(window.localStorage.key(i))==!null){
alert("entered for");
getLocalContent(window.localStorage.key(i));
alert("got local content");
if(document.getElementById(window.localStorage.key(i)).type == "checkbox"){
alert("if");
document.getElementById(window.localStorage.key(i)).checked = true;
}
alert("out of if");
}
}
alert("out of for");
}
}
function storeLocalContent(elementId,value){
window.localStorage.setItem(elementId,value);
}
function getLocalContent(elementId){
document.getElementById(elementId).value = window.localStorage.getItem(elementId);
}
function clear(){
window.localStorage.clear();
}
function removeItem(elementId){
window.localStorage.removeItem(elementId);
}
function isChecked(elementId, value){
if(document.getElementById(elementId).checked == false){
removeItem(elementId);
}
else if(document.getElementById(elementId).checked === true){
storeLocalContent(elementId, value);
}
}
window.onload = function(){
initialize();
}
但每次我“不适合”
最佳答案
这一行的比较运算符是错误的:
if(document.getElementById(window.localStorage.key(i))==!null){
应该是
if(document.getElementById(window.localStorage.key(i))!==null){
关于javascript - 如何使用javascript和localStorage验证元素是否存在于html中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17790593/