首页 > 解决方案 > 试图写一个函数来写更少的代码

问题描述

我有很多“on change”处理程序来将值存储在 localStorage 中。现在我正在尝试缩短我的代码。这是一;

    $('input[name^="tornfalksgrand2"]').on('change', function () {

      let allItems = $('input[name^="tornfalksgrand2"]:checked').map(function(){
        return this.value;
      }).get();
      localStorage['tornfalksgrand2'] = JSON.stringify(allItems)

    });

到目前为止,我尝试了这个功能;

    function addDataToLocalStorage($input, $inputChecked, localStorageName ) {
      $input.on('change', function () {
        let allItems = $inputChecked.map(function(){
          return this.value;
        }).get();
        localStorage[localStorageName] = JSON.stringify(allItems)
      });
   }

然后用这个运行函数;

addDataToLocalStorage($('input[name^="tornfalksgrand2"]'), $('input[name^="tornfalksgrand2"]:checked'), 'tornfalksgrand2');

这将一个空数组存储在 localStorage 中,而不是我想要的值。有人知道吗?

标签: javascriptjqueryfunction

解决方案


推荐阅读