未捕获的TypeError:无法设置属性' src'当想要切换图像时为null

时间:2015-10-25 10:44:48

标签: javascript jquery html image src

我一直在收到Uncaught TypeError:无法设置属性' src'当我想切换图像时出现空错误。

我正在将这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.");
    }
}

这是我的img src

的html代码
    <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>

2 个答案:

答案 0 :(得分:2)

你必须插入&#34; =&#34;你的元素&#39; img 这样的标签:

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

答案 1 :(得分:0)

你必须在你的代码中插入 $(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.");
                   }}
       )};