简体   繁体   English

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

[英]How do I use an array instead of the variables in this repetitive function?

So, I have this little code in my js file: 因此,我的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');
  }
}

The function itself is not important (it equals checkboxvalues set in the localstorage), but I execute it 2 times. 该函数本身并不重要(它等于在localstorage中设置的checkboxvalues),但是我执行了2次。 First time with var a & b set to 'b1' & 'box1' . 第一次将var ab设置为'b1''box1' Then I run the script again (same script), but with var a & b set to 'b2' & 'box2' . 然后,我再次运行脚本(相同的脚本),但是将var ab设置为'b2''box2' Now, this code works, but my question is if there is a shorter way to write this? 现在,这段代码可以用了,但是我的问题是,是否有较短的编写方式? I can imagine some sort of array with a loop, but I could not get it to work for some reason. 我可以想象带有循环的某种数组,但是由于某种原因我无法使其工作。 The 2 variables are pairs, and I know this might be a dumb question, but I can't find the answer anywhere. 这两个变量是成对的,我知道这可能是一个愚蠢的问题,但我在任何地方都找不到答案。

You can use a second function which will accept the local storage key and the checkbox id like 您可以使用第二个函数,该函数将接受本地存储​​密钥和复选框ID,例如

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

function setCheckboxState(id, key) {
    document.getElementById(id).checked = 1 == localStorage.getItem(key);
}
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');

}

?

You might separate common logic into another function 您可以将通用逻辑分为另一个功能

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

This is how I would do it. 这就是我要做的。

There are several problems with your code. 您的代码有几个问题。

  • You do not check that the element you are stetting an attribute to exists. 您不会检查要为其添加属性的元素是否存在。 You do not check if the localStorage item you get is defined. 您无需检查是否定义了您获得的localStorage项。
  • You pollute the global name space with the function name Equal. 您使用函数名称Equal污染了全局名称空间。
  • That function should not be named with a capital as it is not a Object generator. 该函数不应使用大写字母命名,因为它不是对象生成器。
  • There is no need to use setAttribute and removeAttribute , in fact removeAttribute makes no sense in this case as you can not remove the checked attribute from the element. 无需使用setAttributeremoveAttribute ,实际上,在这种情况下removeAttribute没有意义,因为您无法从元素中删除选中的属性。 BTW why use setAttribute here and not for window.onload ? 顺便说一句,为什么在这里使用setAttribute而不对window.onload
  • The checked attribute is either true or false, it does not use the string "checked" checked属性为true或false,它不使用字符串“ checked”
  • Binding the load event via the onload attribute is not safe as you may block 3rd party code, or worse 3rd party code may block you. 通过onload属性绑定load事件并不安全,因为您可能会阻止第三方代码,或者更糟糕的是第三方代码可能会阻止您。
  • There is no error checking. 没有错误检查。 DOM pages are dynamic environments, pages have adverts and content from many places that can interfer with your code. DOM页面是动态环境,页面上的广告和来自许多地方的内容可能会干扰您的代码。 Always code with this in mind. 始终牢记这一点。 Check for possible errors and deal with them in a friendly way for the end user. 检查可能的错误,并以友好的方式对最终用户进行处理。 In this case I used an alert, not friendly for a normal user but for you the coder. 在这种情况下,我使用了一个警报,该警报对普通用户不友好,但对您来说对编码员而言却不友好。

My solution. 我的解决方案。

// 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?");
        }
    }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM