jquery - 在不同的div中迭代多个输入结果
问题描述
我用 3 个 div 做了 3 个不同的输入。输入中的数据从 wiki api 中提取图像。问题是如果我输入例如:input1:dog,input2:cat,input3:potato,我将得到3张与dog相同的图像,并且它会短暂显示cat和potato,但在所有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;
}
});
}
);
});
}
解决方案
试试这个
请检查代码以获取评论。
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>
我希望这会有所帮助并具有解释性。
推荐阅读
- javascript - 如何使用reactjs在点击表格行时打开url
- sql-server - 如何将表名列表传递给 SQL Server 中的存储过程?
- python - 比较 Hive 中表的两个分区
- python-3.x - 带有 apache 身份验证的 REST-API python 请求
- python - 无法加载动态库“cudart64_110.dll”;dlerror: 未找到 cudart64_110.dll
- python - 用于成对比较的弗里德曼检验统计量产生 NaN
- python - 对元组中的最后一个元素求和,其中元组中的前一个元素匹配
- javascript - 我的 if 语句没有做它想做的事
- java - 如何在实体之间创建 JPA 规范连接
- flutter - Flutter:架构 arm64 的未定义符号