首页 > 解决方案 > 使用 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>

标签: javascript

解决方案


该函数被调用(不是undefined问题)

您的代码有 2 个问题。

  1. 您已多次定义x变量。这不被允许。
  2. 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>

推荐阅读