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

时间:2015-09-05 08:42:27

标签: 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) {
    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中设置的复选框值),但我执行了2次。第一次使用var a& b设置为'b1'& 'box1'。然后我再次运行脚本(相同的脚本),但var a& b设置为'b2'& 'box2'。现在,这段代码有效,但我的问题是,是否有更短的方法来编写它?我可以想象某种带循环的数组,但由于某种原因我无法使它工作。 2个变量是成对的,我知道这可能是一个愚蠢的问题,但我无法在任何地方找到答案。

4 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:0)

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');

}

答案 2 :(得分:0)

您可以将常用逻辑分离为另一个函数

window.onload = function Equal() {
  
  function extractFromStorage(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');
    }
  }
  
  extractFromStorage('b1', 'box1');
  extractFromStorage('b2', 'box2');
}

答案 3 :(得分:0)

我就是这样做的。

您的代码存在一些问题。

  • 您不会检查要将属性设置为的元素 存在。您不会检查您获得的localStorage项目是否正确 定义。
  • 您使用函数名称Equal。
  • 污染全局名称空间
  • 该函数不应使用大写命名,因为它不是Object生成器。
  • 无需使用setAttributeremoveAttribute 事实removeAttribute在这种情况下毫无意义,因为你做不到 从元素中删除checked属性。顺便说一句,为什么在这里使用setAttribute而不是window.onload
  • checked属性为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?");
        }
    }
);