我用3格进行了3种不同的输入。输入中的数据从Wiki API获取图像。问题是,如果我输入例如: input1:狗,input2:猫,input3:土豆,我将得到3张与dog相同的图像,并且短暂显示猫和土豆,但在所有3个图像中都是相同的。
很可能我迭代了错误。 这是代码库:https://codepen.io/visan90/pen/QByjKY
有人可以帮忙吗? 预先感谢大家!
<button onclick="imageWp()">Click me</button>
<input class='info' type="text">
<input class='info' type="text">
<input class='info' type="text">
<div class="viewer"></div>
<div class="viewer"></div>
<div class="viewer"></div>
function imageWp() {
let arr = [];
$(".info").each(function(x) {
arr[x] = $(this).val();
$.ajaxPrefilter(function(options) {
if (options.crossDomain && jQuery.support.cors) {
var https = window.location.protocol === "http:" ? "http:" : "https:";
options.url = https + "//cors-anywhere.herokuapp.com/" + options.url;
}
});
$.get(
"https://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text§ion=0&page=" +
arr[x] +
"&callback=?",
function(response) {
var m;
var urls = [];
var regex = /<img.*?src=\\"(.*?)\\"/gim;
while ((m = regex.exec(response))) {
urls.push(m[1]);
}
urls.forEach(function(url) {
$(".viewer")
.empty()
.append('<img src="' + window.location.protocol + url + '">');
if (i === 0) {
return false;
}
});
}
);
});
}
答案 0 :(得分:0)
尝试一下
请检查代码以获取注释。
function imageWp() {
// To avoid lost of data, clear the viewer div before fetching data.
// That's why I move this up here
$(".viewer").empty();
//This will be use to generate div name dynamically
let divNo = 0;
let arr = [];
$(".info").each(function(x) {
arr[x] = $(this).val();
$.ajaxPrefilter(function(options) {
if (options.crossDomain && jQuery.support.cors) {
var https = window.location.protocol === "http:" ? "http:" : "https:";
options.url = https + "//cors-anywhere.herokuapp.com/" + options.url;
}
});
$.get(
"https://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text§ion=0&page=" +
arr[x] +
"&callback=?",
function(response) {
var m;
var urls = [];
var regex = /<img.*?src=\\"(.*?)\\"/gim;
while ((m = regex.exec(response))) {
urls.push(m[1]);
}
urls.forEach(function(url) {
//To make each image appear in different div, put the image in a div and dynamically generate it's id for easy refrence
$(".viewer")
.append('<div id="innerviewer'+ divNo +'"><img src="' + window.location.protocol + url + '"></div>');
//Increment the innerviewer div number
++divNo;
if (i === 0) {
return false;
}
});
}
);
});
}
.viewer{
display:inline;
}
<button onclick="imageWp()">Click me</button>
<input class='info' type="text">
<input class='info' type="text">
<input class='info' type="text">
<div class="viewer"></div>
我希望这个帮助和解释。