Javascript 将内容推送到阵列
我正在尝试将div中的内容添加到数组中。基本上,如果单击苹果、香蕉和猕猴桃的div,生成的数组将按单击顺序存储“苹果、香蕉、猕猴桃”Javascript 将内容推送到阵列,javascript,jquery,arrays,local-storage,Javascript,Jquery,Arrays,Local Storage,我正在尝试将div中的内容添加到数组中。基本上,如果单击苹果、香蕉和猕猴桃的div,生成的数组将按单击顺序存储“苹果、香蕉、猕猴桃” $('.fruit').click(function addFruit() { var fruits = []; var fruit = $(this).text(); fruits.push(fruit); $('.result').text(fruits + ', '); }); 这是我的小提琴: 有什么想法吗 var fruits = []
$('.fruit').click(function addFruit() {
var fruits = [];
var fruit = $(this).text();
fruits.push(fruit);
$('.result').text(fruits + ', ');
});
这是我的小提琴:
有什么想法吗
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
});
ِ附加:我认为不需要在数组中两次推送相同的值,这样您就可以使用
if($.inArray(fruit,fruits) == -1){
// value not in array
}
Make
var fruits=[]代码>全局..尝试以下操作:局部变量fruits
在每次调用时都会重新初始化,因此它将始终丢失推送的单个值。