javascript - 试图写一个函数来写更少的代码
问题描述
我有很多“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 中,而不是我想要的值。有人知道吗?
解决方案
推荐阅读
- php - 注释行之间的匹配
- java - 如何使用 SoapUi 和 Spring boot 自动化 API 测试
- .net-core - 为这项工作准备代理。代理未在 Devops 上运行
- git - 将工作树转换回正常的 git 结构
- javascript - React Native 在组件之间添加间距
- java - 如何在 Java 中使用 selenium Web 驱动程序查找突出显示的文本?
- c# - 使用 Entity Framework Core 编写计算成员
- python - 如何使用python用大小为(8,8)的二维数组替换数组最后一列的前8个元素(大小=(8,8,3))
- grep - 避免在 grep 结果中使用破折号
- flutter - 如何为 gitlab 代码编辑器添加 Flutter 支持