这个基本的JavaScript代码有什么问题?

时间:2011-10-25 17:53:35

标签: javascript javascript-events

我正在尝试编写基本的JavaScript,将段落的背景更改为黄色,然后在点击时将其更改为粉红色。

<p id="foo">Hello, people!</p>

和脚本是

window.onload = function(){
var foo = document.getElementById("foo");
foo.onclick = function(){
        if(foo.style.background!=="yellow")foo.style.background = "yellow";
        if(foo.style.background === "yellow")  foo.style.background = "pink";
};
};

第一次点击时颜色变为黄色,但再次点击时,会变为粉红色。我无法弄清楚问题。

4 个答案:

答案 0 :(得分:7)

编辑:请勿使用background,请使用backgroundColor

Fixed example

    if(foo.style.background!=="yellow")foo.style.background = "yellow";
    if(foo.style.background === "yellow")  foo.style.background = "pink";

需要:

    if(foo.style.background!=="yellow")foo.style.background = "yellow";
    else if(foo.style.background === "yellow")  foo.style.background = "pink";

因为您将其更改为黄色,然后检查它是否为黄色并使其变为粉红色

答案 1 :(得分:0)

尝试更改

if(foo.style.background === "yellow") 

到这个

if(foo.style.background == "yellow") 

答案 2 :(得分:0)

这可能是由于您进行比较的方式:

foo.onclick = function(){
        if(foo.style.background != "yellow") foo.style.background = "yellow";
        if(foo.style.background == "yellow") foo.style.background = "pink";
};

请注意使用“!=”和“==”而不是“!==”和“===”。

答案 3 :(得分:0)

尝试:

var foo = document.getElementById("foo");
foo.onclick = function(){
        if(foo.style.background!="yellow")foo.style.background = "yellow";
        else if(foo.style.background =="yellow")  foo.style.background = "pink";
};

http://jsfiddle.net/AvKPE/

var foo = document.getElementById("foo");
foo.onclick = function(){
        if(foo.style.backgroundColor!="yellow")foo.style.backgroundColor = "yellow";
        else if(foo.style.backgroundColor =="yellow")  foo.style.backgroundColor = "pink";
};

http://jsfiddle.net/AvKPE/2/