简体   繁体   English

使用Javascript在数组中存储键和值

[英]Storing Key and Value using Javascript in array

I have a jsp page on which table is coming dynamically and have checkboxes on that page when you click on that box it should save in array and when it uncheck the box it should remove value from array. 我有一个jsp页面,在该页面上动态生成表,并且在该页面上具有复选框,当您单击该框时,它应该保存在数组中,而当取消选中该框时,它应该从数组中删除值。

I have tried this by creating a method but it is not working perfectly can you please help me.. 我已经尝试过通过创建一种方法来尝试此方法,但是它无法正常运行,请您帮我一下。

function addCheckboxVAlues(checked){
    var split = checked.value.split("|");
    var key =split[0];
    var value=split[1];
    var chks = $("input[name='"+key+"']:checked");
      if (chks.length > 0)  {
         uninvoiced.push(value);
      } else {
         uninvoiced.pop(key);
      }
      console.log(uninvoiced);
}

You need to use splice to remove the element from the array 您需要使用splice从数组中删除元素

function addCheckboxVAlues(checked){
    var split = checked.value.split("|");
    var key =split[0];
    var value=split[1];
    var chks = $("input[name='"+key+"']:checked");
    var index = uninvoiced.indexOf(key);
      if (chks.length > 0)  {
         uninvoiced.push(value);
      } else if(index > -1){
         uninvoiced.splice(index, 1);
      }
      console.log(uninvoiced);
}

This code looks way more complex than it needs to be. 这段代码看起来比需要的复杂得多。 Presumably the checkbox has a click listener on it, so it should be called with the checkbox as this . 大概复选框上有一个单击侦听器,因此应使用复选框this来调用 All you have to do is add the value if the checkbox is checked, or remove it if it's unchecked. 您所要做的就是如果选中此复选框,则添加该值;如果未选中此复选框,则将其删除。

That will be hugely more efficient than running a checked selector every time. 这将比每次运行一个选中的选择器都高效得多。

The following uses an inline listener for convenience, likey you're attaching them dynamically but it seems to be called the same way. 为了方便起见,以下使用内联侦听器,就像您是在动态附加它们一样,但它的调用方式似乎相同。

 var uninvoiced = []; function addCheckbox(el) { var value = el.value.split('|')[1]; if (el.checked) { uninvoiced.push(value); } else { uninvoiced.splice(uninvoiced.indexOf(value), 1); } console.log(uninvoiced); } 
 foo|bar: <input type="checkbox" value="foo|bar" onclick="addCheckbox(this)"> fee|fum: <input type="checkbox" value="fee|fum" onclick="addCheckbox(this)"> 

There is a polyfill for indexOf on MDN . 在MDN上有一个针对indexOf的polyfill

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

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