jQuery每个仅返回最后一个元素,Google Charts API [英] jQuery each returning only last element, Google charts API
问题描述
我有以下代码,它将获取一个数组,并在页面上动态添加一个QR代码,其中文本是数组中的一个元素.
I've the following code which will take an array and append to the page dynamically a QR code with the text being an element in the array.
$(document).ready(function () {
var list = ['dog', 'cat', 'mouse', 'hippo', 'ox'];
var qrUrl = 'https://chart.googleapis.com/chart?';
//functions
function getQrCodes(array) {
$.each(array, function (ix, val) {
//options gets chl property redefined for each element
//in the array
var options = {
cht: 'qr',
chs: '300x300',
chl: array[ix]
}
qrOptionArray.push(options);
console.log('this qr should be: ' + array[ix]);
console.log(qrUrl + $.param(options));
var $img = $('img').attr('src', qrUrl + $.param(options)).appendTo('body');
});
}
getQrCodes(list);
});
您可以在此处看到小提琴的控制台输出,尽管由于某些原因QR码没有显示出现在小提琴窗口中,它们在我的本地计算机上执行.我遇到的问题是,无论您能看到控制台输出是否更改数组中每个元素的事实,最后一个都是我得到的唯一QR码是数组中的最后一个元素重复了X次. 即使控制台输出正确,这些QR罐中的每一个都将扫描并打印'ox' .这里发生了什么?
You can see the console output from the fiddle here although for some reason the QR codes don't appear in the fiddle window, they do on my local machine. The problem I've got is that the last regardless of the fact that you can see the console output change for each element in the array, the only QR code I get is the last element in the array repeated X number of times. Each of those QR cans will scan and print 'ox', even though the console output is correct. What's going on here?
推荐答案
将图像append
传递到正文的选择器是错误的.您正在选择所有现有的img
元素,而您想创建一个新元素.试试这个:
The selector where you append
the image to the body is wrong. You are selecting all existing img
elements, whereas you want to create a new one. Try this:
var $img = $('<img />').attr('src', qrUrl + $.param(options)).appendTo('body');
注意:$('<img />')
不是$('img')
.
这篇关于jQuery每个仅返回最后一个元素,Google Charts API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!