【问题标题】:Adding to list without duplicating publications添加到列表而不复制出版物
【发布时间】:2017-08-12 08:13:34
【问题描述】:

基本上,我想要做的是将数字输入更改添加到出版物列表中。问题是每次我更改输入时都会保留以前的出版物和出版物的数量。例如:

我点击第一个输入 2x,这就是我收到的内容:

出版物 1:数量:1
出版物1:数量:2

应该发生的是,当您单击输入时,它将覆盖以前的数量。比如:

出版物 1:数量:1
出版物 1:数量 2
出版物 2:数量 1

注意删除线。那不应该再存在了。数量已更新。 编解码器

http://codepen.io/Jesders88/pen/evVrrw

HTML

<input type="number" data-name="something here" data-qty="1" data-id="1">
<input type="number" data-name="something else" data-qty="3" data-id="2">
<input type="number" data-name="something other" data-qty="5" data-id="3">

JAVASCRIPT

publications = new Array;

$('input').on('change', function(e){
  e.preventDefault();

  var pid = parseInt($(this).data('id')); // id of thing
  var name = $(this).data('name'); // name of thing
  var qty = parseInt($(this).data('qty'));

  console.log(pid);
  console.log(name);
  console.log(qty);

  if(typeof publications[pid] == 'undefined')
  {
     publications[pid] = new Array;
     publications[pid][0] = name;
     publications[pid][1] = qty;
  }
  else
  {
     publications[pid][1] = qty;
  }

  console.log(publications);

  $.each(publications, function(i, l){
    //console.log( "Index #" + i + ": " + l );
    console.log(l[0]+' has a qty of: '+l[1]);
  });

});

【问题讨论】:

    标签: javascript jquery html arrays associative-array


    【解决方案1】:

    这里有几个问题,最重要的是:您没有更新$(this).data('qty'),因此它始终是相同的值。我个人会使用对象而不是数组,只对qty.value 进行操作,而不是与输入中表示的实际值分离的数据属性:

    // use an object
    var publications = {};
    
    $('input').on('change', function(e){
      e.preventDefault();
    
      var pid = parseInt($(this).data('id'), 10); // id of thing
      var name = $(this).data('name'); // name of thing
      var qty = parseInt($(this).val(), 10);
    
      // if you must, set the new quantity into the data property
      $(this).data('qty', qty);
    
      console.log(pid);
      console.log(name);
      console.log(qty);
    
      if(!publications[pid])
      {
         publications[pid] = {
           name: name,
           qty: qty
         };
      }
      else
      {
         publications[pid].qty = qty;
      }
    
      console.log(publications);
    
      $.each(publications, function(i, l){
        //console.log( "Index #" + i + ": " + l );
        console.log(l.name+' has a qty of: '+l.qty);
      });
    
    });
    

    【讨论】:

    • 太棒了。很简单。我不敢相信我错过了:)。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    相关资源
    最近更新 更多