javascript - 使用 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 个问题。
- 您已多次定义
x
变量。这不被允许。 if (x = 0) {
始终是错误的,我认为应该将其更改为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>
推荐阅读
- c# - 在 Unity 中对我的库存系统实施堆叠
- django - 不确定 Django 自定义用户组和权限的方法
- google-sheets - 使用 IFTEXT 在谷歌表格上使用多个参数的问题
- amazon-web-services - Amazon DynamoDB 扫描未扫描完整表
- javascript - 对多个 JS 文件中的 API 密钥使用 dotenv
- python - 计算两个不同数据框中坐标之间的距离
- javascript - 如何制作虚线和实线甜甜圈 Chart.js
- powershell - 启动进程内的启动进程作为不同的用户
- google-directions-api - 使用 Google Directions 或 Azure Routing API 以特定固定航点顺序优化车辆路线?
- python - 如何在 Python 中对多个嵌套 for 循环使用多处理?