[英]Loading an img object with a src in javascript
我想在網頁上從谷歌圖書 api 派生的書籍詳細信息中添加縮略圖。 下面的代碼將放置相應書籍的源代碼 (api),首先放入文本字段 bookCover 中,然后放入 var copyPic 中,然后應該將其復制到 imgDisp 中,但它沒有。 我可以看到 bookCover 包含正確的文本,並檢查了 copyPic 包含正確的內容。
<img id="imgDisp" src="http://books.google.com/books/content?
id=YIx0ngEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api" width="85" height="110"" />
$.getJSON(googleAPI, function(response) {
$("#title").html(response.items[0].volumeInfo.title);
$("#subtitle").html(response.items[0].volumeInfo.subtitle);
$("#author").html(response.items[0].volumeInfo.authors[0]);
$("#description").html(response.items[0].volumeInfo.description);
$("#version").html(response.items[0].volumeInfo.contentVersion);
$("#modeR").html(response.items[0].volumeInfo.readingModes.text);
$("#bookCover").html(response.items[0].volumeInfo.imageLinks.thumbnail);
var copyPic = document.getElementById('bookCover').innerHTML;
document.getElementById("imgDisp").src=copyPic;
有誰知道為什么不? 或者我可以將api詳細信息直接放入imgDisp(在網上的任何地方都找不到這樣的代碼語法)? 其他一切正常。 如果我直接放入一個 src ,那么它就可以工作,例如
document.getElementById("imgDisp").src = “http://.....api”
但不是帶有變量。
沒有更多信息 - 例如,我看不到 getJSON() 函數在哪里結束或 URL 是什么,我看不到問題可能是什么(除了,也許,就像我上次評論一樣)。
我的想法似乎沒問題,因為我可以復制它(當然是精簡版):
function copyImageSource() { let d = document.getElementById("bookCover").innerHTML; document.getElementById("imgDisp").src = d; }
<button onclick="copyImageSource();">Get image</button> <div id="bookCover">https://duckduckgo.com/assets/icons/meta/DDG-icon_256x256.png</div> <img id="imgDisp" src="">
我認為這是您想要實現的目標?
(javascript -> jquery:
let copyPic = $("#bookCover").html();
$("#imgDisp").attr("src", copyPic);
)
使用 jquery 的版本:
function copyImageSource() { let d = $("#bookCover"); d.html("http://books.google.com/books/content?id=YIx0ngEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api"); let dCopy = d.html().replace(/&/g, "&"); $("#imgDisp").attr("src", dCopy); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="copyImageSource();">Get image</button> <div id="bookCover"></div> <img id="imgDisp" src="https://www.picsearch.com/images/logo.png"/>
如果您有 jQuery,您可以輕松地執行以下操作:
let source = 'https://img.com/image.png';
//to get the image object that has the above just do this:
let img = $('img[src="' + source + '"]');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.