2017-03-01 71 views
2

我有这段代码,我想知道如何让我的图像使用jQuery加载到我的网站上。如何使用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”变量是我需要使用的吗?我被告知,我的图像将加载在绝对路径上,但我认为这些图像是在相对路径上的,因为它来自Wikipedia API。

+0

'$( “containerElement”)追加( '');' –

回答

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]+'" />'); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div id="images"></div>