我是javascript编程的新手。 当我尝试运行此代码时,html标记中的默认图像显示出来。 我使用了setAttribute函数,但它不起作用。请帮助!
<!DOCTYPE HTML>
<html>
<head>
<title>Javascript</title>
<script type="text/javascript">
var foo = document.getElementById("image");
foo.setAttribute("src", "glasses.jpg");
</script>
</head>
<body>
<img src="awesomesite.gif" id="image" alt="Awesomesite">
<p id="intro">
Hello World
</p>
</body>
</html>
答案 0 :(得分:2)
将脚本移动到页面底部或将以下内容添加到脚本
document.onload(function()
{
var foo = document.getElementById("image");
foo.setAttribute("src", "glasses.jpg");
});
答案 1 :(得分:1)
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<style>
</style>
</head>
<body>
<img src="http://i.stack.imgur.com/xkF9Q.jpg" id="image" alt="Awesomesite">
<p id="intro">
Hello World
</p>
<script>
window.onload = function () {
var logo = document.getElementById('image');
logo.src = "http://www.w3schools.com/html/pic_mountain.jpg";
};
</script>
</body>
</html>