JavaScript更改图像的来源

时间:2015-12-01 13:17:10

标签: javascript html css

我正在尝试通过JavaScript替换图像。我现在拥有的是这个HTML:

<div class="col-md-4 " id="demo3">
    <input type="image" src="intro.jpg" width="600px" onclick="gamepaper();" />
</div>

和这个JavaScript:

document.write("<input type='image' src='intro-win.jpg' width='600px' />");

现在的问题是,此图片现在位于新页面上,并不会替换旧图像。

我想过制作一个像这样的功能:

function changeSource() {
    var image = document.querySelectorAll("img")[0];
    var source = image.src = image.src.replace("placeholder.png","01.png");
};  

但这也不起作用。

3 个答案:

答案 0 :(得分:1)

您需要使用input代码:

function changeSource() {
    var image = document.querySelectorAll("input")[0];
    var source = image.src = image.src.replace("placeholder.png","01.png");
};

但更好的方法是添加ID并定位它:

document.write("<input type='image' src='intro-win.jpg' width='600px' id='MyImg' />");

function changeSource() {
    var source = MyImg.src = MyImg.src.replace("placeholder.png","01.png");
};

答案 1 :(得分:1)

您在html中使用input type image,但在js搜索img。这应该如下所示:

var image = document.querySelectorAll("input[type=image]")[0];

答案 2 :(得分:0)

只需为您的图片添加ID,然后在document.ready函数上使用该ID并更改源代码。

<div class="col-md-4 " id="demo3">
    <input id="myImage" type="image" src="intro.jpg" width="600px" onclick="gamepaper();" />
</div>

在下一页

$(document).ready(function() {
   $('#myImage').attr("src", "myOtherSource.jpg");
});
相关问题