Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/438.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在这个重复函数中使用数组而不是变量?_Javascript_Arrays_Loops - Fatal编程技术网

Javascript 如何在这个重复函数中使用数组而不是变量?

Javascript 如何在这个重复函数中使用数组而不是变量?,javascript,arrays,loops,Javascript,Arrays,Loops,因此,我的js文件中有一个小代码: window.onload = function Equal() { var a = 'b1' var b = 'box1' var bookstorname = localStorage.getItem(a) if (bookstorname == 1) { document.getElementById(b).setAttribute('checked','checked'); } if (bookstorname == 0

因此,我的js文件中有一个小代码:

window.onload = function Equal() {
  var a = 'b1'
  var b = 'box1'
  var bookstorname = localStorage.getItem(a)
  if (bookstorname == 1) {
    document.getElementById(b).setAttribute('checked','checked');
  }
  if (bookstorname == 0) {
    document.getElementById(b).removeAttribute('checked','checked');
  }
  var a = 'b2'
  var b = 'box2'
  var bookstorname = localStorage.getItem(a)
  if (bookstorname == 1) {
    document.getElementById(b).setAttribute('checked','checked');
  }
  if (bookstorname == 0) {
    document.getElementById(b).removeAttribute('checked','checked');
  }
}
函数本身并不重要(它等于localstorage中设置的checkboxvalue),但我执行了2次。第一次将
var
a
&
b
设置为
'b1'
&
'box1'
。然后我再次运行脚本(相同的脚本),但是
var
a
&
b
设置为
'b2'
&
'box2'
。现在,这段代码可以工作了,但我的问题是,是否有一种更短的方法来编写这段代码?我可以想象某种带有循环的数组,但由于某种原因,我无法让它工作。这两个变量是成对的,我知道这可能是一个愚蠢的问题,但我在任何地方都找不到答案

function doTheStuff(a, b) {

  var bookstorname = localStorage.getItem(a)

  if (bookstorname == 1) {

    document.getElementById(b).setAttribute('checked','checked');

  }

  if (bookstorname == 0) {

    document.getElementById(b).removeAttribute('checked','checked');

  }  

}



window.onload = function Equal() {

  doTheStuff('b1', 'box1');

  doTheStuff('b2', 'box2');

}

您可以使用第二个函数,该函数将接受本地存储密钥和复选框id,如

window.onload = function Equal() {
    setCheckboxState('box1', 'b1');
    setCheckboxState('box2', 'b2');
}

function setCheckboxState(id, key) {
    document.getElementById(id).checked = 1 == localStorage.getItem(key);
}

您可以将公共逻辑分离到另一个函数中

window.onload=函数相等(){
从存储器中提取函数(a,b){
var bookstorname=localStorage.getItem(a)
if(bookstorname==1){
document.getElementById(b).setAttribute('checked','checked');
}
if(bookstorname==0){
getElementById(b).removeAttribute('checked','checked');
}
}
从存储器中提取('b1','box1');
从存储器中提取('b2','box2');

}
我就是这样做的

您的代码有几个问题

  • 您不检查正在向其添加属性的元素 存在。您不检查您获得的
    localStorage
    项是否为 定义
  • 如果函数名相等,则会污染全局名称空间
  • 该函数不应使用大写字母命名,因为它不是对象生成器
  • 在中不需要使用
    setAttribute
    removeAttribute
    事实
    removeAttribute
    在这种情况下没有意义,因为您不能 从元素中删除选中的属性。顺便问一下,为什么在这里使用
    setAttribute
    ,而不是
    window.onload
  • 选中的
    属性为true或false,它不使用
    字符串“选中”
  • 通过onload属性绑定load事件可能不安全 阻止第三方代码,或者更糟糕的是,第三方代码可能会阻止您
  • 没有错误检查。DOM页面是动态环境、动态页面 有来自许多地方的广告和内容可以干扰你的网站 代码。在编写代码时始终牢记这一点。检查可能出现的错误,并以友好的方式为最终用户处理。在本例中,我使用了一个警报,对普通用户来说不友好,但对编码人员来说是友好的
我的解决方案

// add an event listener rather than replace the event listener
window.addEventListener(
    "load",  // for the load event
    function(){

        // the update function that is called for each item;
        var update = function(item){
            // the right hand side equates to true if the localstorage
            // is equal to "1". LocalStorage allways returns a string or
            // undefined if the key is not defined.
            item.element.checked = localStorage[item.storageName] === "1";
        }   

        // safe element getter     
        var getElement = function(eId){
            var e = document.getElementById(eId); // try and get the element
            if(e === null){  // does it exist?
                throw "Missing element:"+eId;  // no then we can not continue
                                               // the program stops here unless
                                               // you catch the error and deal with 
                                               // it gracefully.
            }
            return e; //ok return the element.
        }

        // Item creator. This creates a new item.
        // sName is the local storage name
        // eId id the element ID
        var item = function(sName, eId){
            return {
                storageName: sName,  // set the loaclStorage name
                element:getElement(eId); // get the element and check its safe
            };
        }

        // make it all safe
        try{
            // create an array of items.
            var items = [
                item("b1","box1"),
                item("b2","box2")
            ];
            // for each item update the element status
            items.forEach(update);
        }catch(e){
            alert("Could not update page?");
        }
    }
);

+1用于使用
.checked
属性,而不是添加和删除
checked
属性(这意味着
.defaultChecked
),只要指出如果添加了
'use strict'
,则该代码将抛出错误,因为
bookstorname
未定义。如果不使用
“使用严格的”
它将不正确地选中复选框,因为
bookstorname
未定义的
,如果未找到与
未定义的
相同的本地存储,也会导致
为true
@Blindman67抱歉。。。假设它是
1==localStorage.getItem(key)
localStorage返回字符串,所以最好使用
“1”==localStorage[key]getItem
更有效。添加
else
语句而不是第二次比较。这将涵盖未定义本地存储的情况<代码>}if(bookstorname==0){
变成
}else{
并停止运行不必要的代码。感谢您指出我的错误,我几天前才开始学习JavaScript,所以我很感激。但不必担心,这一切都是为了一个脱机文档。当我把它放到联机时(如果有的话),我将学习如何正确语法和使用JavaScript。当然,我在w3schools和一些vids上了这门短期课程,但除此之外,学习js的最佳方法是什么?