<script>
function img(){
var x=document.getElementById("demo");
x.src="img/bj/bj2.png";
}
</script>
</head>
<body>
<h1>我的第一个 JavaScript 程序</h1>
<p id="demo"><img src="img/bj/bj1.png" width="800" height="400"></p>
<button type="button" onclick="img()">修改</button>
点击按钮没有修改还是原图
应该是获取img元素修改src,而不是p元素。document.getElementsByTagName('img')[0].src="img/bj/bj2.png"
把id放到img里,改成如下,
<script>
function img(){
var x=document.getElementById("demo");
x.src="img/bj/bj2.png";
}
</script>
</head>
<body>
<h1>我的第一个 JavaScript 程序</h1>
<p><img id="demo" src="img/bj/bj1.png" width="800" height="400"></p>
<button type="button" onclick="img()">修改</button>
<!DOCTYPE html>
<html>
<head>
<script>
function img(){
var x=document.getElementById("demo").getElementsByTagName("img");
x[0].src="img/bj/bj2.png";
}
</script>
</head>
<body>
<h1>我的第一个 JavaScript 程序</h1>
<p id="demo"><img src="img/bj/bj1.png" width="800" height="400"></p>
<button type="button" onclick="img()">修改</button>
</body>
</html>
<script>
function img(){
var x=document.getElementById("demo");
x.src="img/bj/bj2.png";
}
</script>
</head>
<body>
<h1>我的第一个 JavaScript 程序</h1>
这个地方吧id给img标签
<p ><img id="demo" src="img/bj/bj1.png" width="800" height="400"></p>
<button type="button" onclick="img()">修改</button>
吧id给img标签就好了