Rou*_*ren 3 javascript arrays jquery local-storage
我正在尝试将div中的内容添加到数组中.基本上如果你单击Apple,Banana和Kiwi的div,结果数组将按照它们被点击的顺序存储'Apple,Banana,Kiwi'.
$('.fruit').click(function addFruit() {
var fruits = [];
var fruit = $(this).text();
fruits.push(fruit);
$('.result').text(fruits + ', ');
});
Run Code Online (Sandbox Code Playgroud)
这是我的小提琴:https://jsfiddle.net/bjhj5p41/2/
有任何想法吗?
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
});
Run Code Online (Sandbox Code Playgroud)
附加:我认为不需要在数组中两次推送相同的值,以便您可以使用
if($.inArray(fruit,fruits) == -1){
// value not in array
}
Run Code Online (Sandbox Code Playgroud)