添加到列表而不重复发布

时间:2017-03-20 21:06:39

标签: javascript jquery html arrays associative-array

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

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

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

当你点击一个输入它会覆盖以前的数量时应该发生什么。例如:

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

注意删除线。那应该不复存在了。数量已更新。 CODEPEN

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

HTML

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

Sub Macro1()
'
' Macro1 Macro
'

' Paste a value into another sheet if the value is not a formula.

    Dim sourcecell As Range
    Dim targetcell As Range

    Set sourcecell = Sheets(1).Range("D8")
    Set targetcell = Sheets(2).Range("D8")

    If Not sourcecell.HasFormula Then targetcell = sourcecell

End Sub

1 个答案:

答案 0 :(得分: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);
  });

});