我正在尝试使用一些简单的Javascript函数来更改<img>
当按下按钮时,将来源转换为另一张图片。
但是,这些按钮似乎都不起作用,甚至是我为了测试是否会收到警报而制作的最后一个按钮也不起作用。
我尝试找出问题所在,但似乎找不到。我已经搜索过类似的问题和线程,但解决方案从未适用于我的案例......
谢谢。 (我只发布了 <body></body>
标签,因为 <head>
和 co. 标签没有什么特别的)
<script type="text/javascript">
function myFunctionMice() {
document.getElementById("target").src = "http://www.clker.com/cliparts/b/Z/f/0/p/W/mouse-with-smaller-ears-md.png">;
};
function myFunctionLaser() {
document.getElementById("target").src = "http://www.clker.com/cliparts/b/Z/f/0/p/W/mouse-with-smaller-ears-md.png" >;
};
function myFunctionBirds() {
document.getElementById("target").src = "http://image.flaticon.com/icons/png/512/47/47080.png">;
};
function myTry() {
alert("example");
};
</script>
<h1 align="center">Web4Cats</h1>
<nav>
<button type="button" onclick="myFunctionBirds()">Birds</button>
<button type="button" onclick="myFunctionMice()">Mice</button>
<button type="button" onclick="myFunctionLaser()">Laser</button>
<button type="button" onclick="myTry()">Try</button>
</nav>
<img id="target" src="http://www.clker.com/cliparts/b/Z/f/0/p/W/mouse-with-smaller-ears-md.png">
最佳答案
您的代码中有语法错误。这个 >;
需要删除。否则你的 src 无效。请看下面的代码片段,看看您的方法是否正确。
function myFunctionMice() {
document.getElementById("target").src = "http://www.clker.com/cliparts/b/Z/f/0/p/W/mouse-with-smaller-ears-md.png"
};
function myFunctionLaser() {
document.getElementById("target").src = "http://www.clker.com/cliparts/b/Z/f/0/p/W/mouse-with-smaller-ears-md.png"
};
function myFunctionBirds() {
document.getElementById("target").src = "http://image.flaticon.com/icons/png/512/47/47080.png"
};
function myTry() {
alert("example");
};
<h1 align="center">Web4Cats</h1>
<nav>
<button type="button" onclick="myFunctionBirds()">Birds</button>
<button type="button" onclick="myFunctionMice()">Mice</button>
<button type="button" onclick="myFunctionLaser()">Laser</button>
<button type="button" onclick="myTry()">Try</button>
</nav>
<img id="target" src="http://www.clker.com/cliparts/b/Z/f/0/p/W/mouse-with-smaller-ears-md.png">
关于javascript - 无法理解为什么我的 Javascript 函数不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45542371/