在JavaScript中使用src加载img对象

问题描述

我想在网页的Google图书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的位置,看不到问题的根源(也许,如我上次评论中所述)。 / p>

我的想法似乎还可以,因为我可以复制它(当然是简化版):

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(/&amp;/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 + '"]');