简体   繁体   中英

Js function not defined

I was working on a simple show and hide function and it kept telling me that it's not defined.

Here's the HTML:

<address>
<a id="windows" href="#" onclick="toggle();">
<img src="imges/c980e3f5-badf-432a-ae6c-9e5341d13462.png" alt="" />
</a>
</address>
         <p class="right_page">
           this is sample of the book container<br/>
           thats suppose to read from ajax
            </p>

and here the function

    <script type="text/javasript">
function toggle() 
{
    var ele = document.getElementById("right_page");
    var text = document.getElementById("windows");
    if(ele.style.display == "block") {
            ele.style.display = "none";
        text.innerHTML = "show";
    }
    else {
        ele.style.display = "block";
        text.innerHTML = "hide";
    }
} 

</script> 

I think it is due to a typo in your script tag. Change type="text/javasript" to type="text/javascript" (missing the c ).

Update

Your image is being removed from the DOM due to you setting the innerHtml to a string. This overwrites the image which is part of the innerHtml.

The first time that you run toggle() there is not an inline style for display so ele.style.display will be an empty string. This means that it will drop into the logic for showing the paragraph. On subsequent calls the property will have a value so it should behave as you expect.

There are a couple of things wrong here:

  1. Did you paste this in directly from your code? If so, your <script type... line contains a typo (should be "javas* c *ript")

  2. You can't use getElementById() for right_page as it stands, because right_page is only defined as a class in your mark-up.

First you missed the C change type="text/javascript" , second the right_pae is not a ID , can't use document.getElementById because there are something wrong with your function, so it tells you the function is undefined

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM