基本的Javascript问题

sup*_*er9 -1 javascript if-statement

我正在搞乱Head First Javascript书.所以我的问题是为什么if我的函数中的子句不会turnSad()触发?更新我在Chrome和FF4中尝试过这个.另外,如果我要对if语句进行注释,该函数将起作用.

<script type="text/javascript">

    function turnSad() {
        if (document.getElementById("rockImg").src == "rock_happy.png")
            document.getElementById("rockImg").src = "rock.png";
    }

    function touchRock() {
        var userName = prompt("What is your name?", "Enter your name here");

        if (userName) {
            alert("It is nice to meet you " + userName + ".");
            document.getElementById("rockImg").src = "rock_happy.png";
        }
        setTimeout("turnSad();", 1000);
    }

</script>
<img id="rockImg" src="rock.png" alt="iRock"  style="cursor:pointer" 
    onclick="touchRock();" />
Run Code Online (Sandbox Code Playgroud)

Anu*_*rag 7

当访问src属性(不是属性)时,浏览器可以自动解析相对路径并返回绝对路径,包括协议,域,端口等.

要获取或更改属性值,请使用getAttributesetAttribute.

image.getAttribute("src");

image.setAttribute("src", "someImage.png");
Run Code Online (Sandbox Code Playgroud)

看这个例子.

  • `src`属性存在于[DOM对象](https://developer.mozilla.org/en/DOM/HTMLImageElement)上,表示HTML文档中的`<img>`.另一方面,`src`属性表示HTML文档中存在的`src`属性的原始值.获取或设置属性值时,不会对该值应用任何逻辑,也不会以任何方式进行转换. (2认同)