使用if-else语句时未定义函数



当我点击页面上的pierre按钮时,图像应该会发生变化,我知道行可以工作,但当我按下按钮时,它说函数没有定义,我尝试更改标签上的id,但也没有起作用,我只是非常困惑

<!DOCTYPE html>
<html>
<head>
<title>Pierre Omidyar</title>
</head>

<script>
var x = 0
function pierre() {
if (x = 0) {
document.getElementById('myImage').src='https://cdn3.pitchfork.com/longform/699/Pierre1.jpg'; 
var x = 1
} else {
var x = 0
}
} 
</script>
<body>
<button onclick="pierre()" type="button">pierre</button>
<br>
<img height=50%  width=50% id="myImage" src="https://upload.wikimedia.org/wikipedia/commons/0/0b/Pierre_Omidyar_%2850911249%29.jpg"/>
<audio loop id="no"><source src="https://codehs.com/uploads/9af74ff56cf4b8ed3809fba276efa59e" type="audio/mpeg"></audio>
<p id="para">Hi, I'm Pierre Omidyar, I made eBay</p>
</body>
</html>

调用函数(不是undefined问题(

你的代码有2个问题。

  1. 您已经多次定义x变量。这是不允许的
  2. if (x = 0) {总是false,我认为应该将其更改为x == 0

现在,这个代码就可以工作了。

<!DOCTYPE html>
<html>
<head>
<title>Pierre Omidyar</title>
</head>

<script>
var x = 0;
function pierre() {
if (x == 0) {
document.getElementById('myImage').src='https://cdn3.pitchfork.com/longform/699/Pierre1.jpg'; 
x = 1;
} else {
x = 0;
}
} 
</script>
<body>
<button onclick="pierre()" type="button">pierre</button>
<br>
<img height=50%  width=50% id="myImage" src="https://upload.wikimedia.org/wikipedia/commons/0/0b/Pierre_Omidyar_%2850911249%29.jpg"/>
<audio loop id="no"><source src="https://codehs.com/uploads/9af74ff56cf4b8ed3809fba276efa59e" type="audio/mpeg"></audio>
<p id="para">Hi, I'm Pierre Omidyar, I made eBay</p>
</body>
</html>

您的代码中存在多个问题。这是更新后的代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script type="text/javascript">
var x = 0;
function pierre() {
if (x === 0) {
document.getElementById('myImage').src = 'https://cdn3.pitchfork.com/longform/699/Pierre1.jpg';
x = 1
}
else {
x = 0
}
}
</script>
</head>
<body>
<button onclick="pierre()" type="button">pierre</button>
<br>
<img height=50%  width=50% id="myImage" src="https://upload.wikimedia.org/wikipedia/commons/0/0b/Pierre_Omidyar_%2850911249%29.jpg"/>
<audio loop id="no">
<source src="https://codehs.com/uploads/9af74ff56cf4b8ed3809fba276efa59e" type="audio/mpeg">
</audio>
<p id="para">Hi, I'm Pierre Omidyar, I made eBay</p>
</body>
</html>

最新更新