将内容推送到数组
Pushing content to array
我正在尝试将 div 中的内容添加到数组中。基本上,如果您单击 Apple、Banana 和 Kiwi 的 div,生成的数组将按照单击它们的顺序存储 'Apple, Banana, Kiwi'。
$('.fruit').click(function addFruit() {
var fruits = [];
var fruit = $(this).text();
fruits.push(fruit);
$('.result').text(fruits + ', ');
});
这是我的 fiddle: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
});
ِAdditional: 我认为不需要在数组中两次推送相同的值所以你可以使用
if($.inArray(fruit,fruits) == -1){
// value not in array
}
我正在尝试将 div 中的内容添加到数组中。基本上,如果您单击 Apple、Banana 和 Kiwi 的 div,生成的数组将按照单击它们的顺序存储 'Apple, Banana, Kiwi'。
$('.fruit').click(function addFruit() {
var fruits = [];
var fruit = $(this).text();
fruits.push(fruit);
$('.result').text(fruits + ', ');
});
这是我的 fiddle: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
});
ِAdditional: 我认为不需要在数组中两次推送相同的值所以你可以使用
if($.inArray(fruit,fruits) == -1){
// value not in array
}