Uncaught TypeError: Cannot set property 'src' of null when want to switch the image

Uncaught TypeError: Cannot set property 'src' of null when want to switch the image

当我想切换图像时,我不断收到 Uncaught TypeError: Cannot set 属性 'src' of null 错误。

我将这 2 个文件用于 jquery

<script language="JavaScript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script language="JavaScript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.5.2/jquery-ui.min.js"></script>

这是 javascript 代码

function correctcheck() {

    var value = document.getElementById("codes").value;
    var img = document.getElementById("gameplay");
    if (value == "$player //Declare player as an object\n\n$player = 'Artix' //Set player to Artix\n\necho = 'I am'.$player.'I got the key' // Echo the message\n\n") {
        img.src="correct.gif"; //error is here
        window.alert("Congratulation. You passed forest level.");


   return false;

    } else {
        window.alert("Your Drag and drop code is incorrect..View tips to get correct answer.");
    }
}

这是我的 html img 源代码

    <div class="featured">
        <div class="wrap-featured grid">
            <div class="slider">
                <img  src="Artix.png" alt = "GameBanner" name="gameplay" id "gameplay"/>
                <textarea name="codes" id="codes" class="txtDropTarget" cols="80" rows="10"></textarea>
                <a class="button" onClick="correctcheck()"  >Run</a>

            </div>
        </div>
    </div>

您必须在您的代码中插入 $(document).ready 并且在您的 img 中插入“=”元素像这样的标签:

<img  src="Artix.png" alt = "GameBanner" name="gameplay" id="gameplay"/>

function correctcheck() {
       $(document).ready(function(){
           var value = document.getElementById("codes").value;
           var img = document.getElementById("gameplay");
                  if (value == "$player //Declare player as an object\n\n$player = 'Artix' //Set player to Artix\n\necho = 'I am'.$player.'I got the key' // Echo the message\n\n") {
                    img.src="correct.gif"; //error is here

                    window.alert("Congratulation. You passed forest level.");
                    return false;
                } else 
                    {
                   window.alert("Your Drag and drop code is incorrect..View tips to get correct answer.");
                   }}
       )};

您必须在 img 标签中插入“=”元素,如下所示:

<img  src="Artix.png" alt = "GameBanner" name="gameplay" id="gameplay"/>