将内容推送到数组

时间:2015-12-16 04:07:43

标签: javascript jquery arrays local-storage

我试图将div中的内容添加到数组中。基本上如果你单击Apple,Banana和Kiwi的div,结果阵列将存储Apple,Banana,Kiwi和#39;按照他们点击的顺序。

$('.fruit').click(function addFruit() {
  var fruits = [];
  var fruit = $(this).text();
  fruits.push(fruit);
  $('.result').text(fruits + ', ');
});

这是我的小提琴:https://jsfiddle.net/bjhj5p41/2/

有什么想法吗?

1 个答案:

答案 0 :(得分:6)

var fruits = [];  // make it global
$('.fruit').click(function() { // no need to use addFruit here
  var fruit = $(this).text();
  fruits.push(fruit);
  $('.result').text(fruits); // use (fruits) cause its an array it will return commas itself
});

Working Demo

附加:我认为无需在数组中两次推送相同的值,以便您可以使用

if($.inArray(fruit,fruits) == -1){
   // value not in array
}

Demo