开发者

javascript functions only working once

I have these two javascript functions that change a background and show and hide fields, however it only works once for each button

function showabout(){


        hidecontact = document.getElementById("contactus");

        hidecontact.style.display = "none";


        hide.style.backgroundImage = "url(aboutus.jpg)";


        showabout = document.getElementById("aboutus");
        showabout.style.display = "inline";
        showabout.style.cssFloat = "left";
        secbuttons.style.paddingLeft = "670px";




        }

        function showcontact(){


        hideabout = document.getElementById("aboutus");
        hideabout.style.display = "none";   


        hide.style.backgroundImage = "url(contact.jpg)";


        showcontact = document.getElementById("contactus");
        showcontact.style.display = "inline";
        showcontact.style.cssFloat = "left";
        secbuttons.style.paddingLeft = "670px";




        }


   <font color="#33FF66"><h2 style="cursor:pointer" onmouseover = "showabout()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</h2></font>

<font color="#33FF66"><h2 style="cursor:pointer" onclick="showcontact()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</h2></font>开发者_开发问答;<br />

<font color="#33FF66"><h2 style="cursor:pointer" onmouseover = "showcontact()">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</h2></font>

The three H2s are the lines causing the errors. It says "uncaught type error, object is not a function".


Your problem is that you're redefining showabout and showcontact — your functions — to refer to HTML elements.

These two code snippets:

function showabout() {
    ...
}

and

showabout = document.getElementById("aboutus");

both set the variable window.showabout. The first one assigns a function to window.showabout, and the latter assigns an HTML element to window.showabout.

Because you don't use the var keyword to declare the variables in your functions, showabout = document.getElementById("aboutus") reassigns showcontact to refer to that element instead of the function you're defining. So then when you try to call showcontact() a second time, it doesn't work because showcontact is no longer a function.

The easy fix is actually an all-around good rule whenever you're writing JavaScript:

Always declare your variables

There's also a second lesson here:

Give your variables descriptive names

Although your code will work if you just declare the showabout variable ahead of time, it will still be confusing to read. The function and the element it shows should have different names. Say, call the function showAboutBox and the box it shows aboutBox. This way there's no room for confusion — either by you or the language — about which thing you're referring to.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜