我有这段代码,我想知道如何使用jQuery在我的网站上加载我的图像。
$.getJSON('https://en.wikipedia.org/w/api.php?action=parse&page=New_Jersey&prop=text&format=json&callback=?', function(json) {
const text = json.parse.text['*'];
const regex = /([-\w+\.\/]+(?:png|svg))/gmi;
let m;
while ((m = regex.exec(text)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
picture = regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
console.log(`Found match: ${m[1]}`);
}});
图片在我的控制台上加载,但是他们不会加载到我的实际页面上。如何在HTML页面上显示图像?那是" m"变量我需要使用什么?有人告诉我,我的图像会加载到绝对路径上,但我认为这些图像是在相对路径上,因为它来自维基百科API。
答案 0 :(得分:2)
使用jQuery,只需将img
元素附加到DOM上的元素:
$.getJSON('https://en.wikipedia.org/w/api.php?action=parse&page=New_Jersey&prop=text&format=json&callback=?', function(json) {
const text = json.parse.text['*'];
const regex = /([-\w+\.\/]+(?:png|svg))/gmi;
let m;
while ((m = regex.exec(text)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
picture = regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
$('#images').append('<img src="'+m[0]+'" />');
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="images"></div>
&#13;