在图像src中添加另一个变量?

时间:2016-06-08 19:37:01

标签: javascript jquery string image src

<img src="blank.png" id="image" alt="just nothing">

<script type="text/javascript">
document.getElementById('image').src = '"'+ img +'"';
var img = new Image();
img.src = "https://pbs.twimg.com/profile_images/696014803844927488/8aLamHjS.jpg";
</script>

它不起作用。我很困惑。

2 个答案:

答案 0 :(得分:0)

您在声明变量之前访问变量image,您的代码应如下所示:

var img = new Image();
img.src = "https://pbs.twimg.com/profile_images/696014803844927488/8aLamHjS.jpg";

document.getElementById('image').src = img.src;

查看此fiddle

答案 1 :(得分:0)

将您的代码更改为此

&#13;
&#13;
var img = "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png";
document.getElementById('image').src = img ;
&#13;
<img src="blank.png" id="image" alt="just nothing">
&#13;
&#13;
&#13;

您可以直接申请src

&#13;
&#13;
 document.getElementById('image').src = "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png";
    
&#13;
<img src="blank.png" id="image" alt="just nothing">
&#13;
&#13;
&#13;