if (document.getElementById) {
function alterImg() {
document.body.getElementById('sendimg').src="url('images/tridown.png')";
}
}
然后是 html:
<div id="sendbutton">
<img id="sendimg" src="images/tri.png" onclick="alterImg()" />
</div>
我也尝试使用 this 关键字引用,但没有成功。
最佳答案
您的代码存在三个问题:
- 您使用的文档.body .getElementById。 “
getElementById
”是document
的方法,而不是body元素的方法。 - 您将 css 与 html 混合在一起。在 html 中,您可以将 url 分配给图像的
src
属性。在 css 中,您可以使用url(...)
来引用图像,例如用于背景。 - 您在 if 语句中使用函数声明。请注意,这确实在当前作用域(我假设是全局的)中声明了该函数,无论 if block 是否被执行。如果您只想在
document.getElementById
可用时定义该函数,则需要使用
if (document.getElementById) {
var alterImg = function () {
document.getElementById('sendimg').src="images/tridown.png";
}
}
关于javascript - 仍然遇到简单的 JavaScript 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10644808/