开发者

simple onclick event not working

I've got quite a simple set up with html, css, and javascipt. When the user clicks on one of the many divs there are, it should either appear or disappear, as well as setting a hidden form field to "1" or "0".

First, the css:

div.hidden{
    visibility: hidden;
}
div.shown{
    visibility: visible;
}

javascript:

function toggle(id){
    if (document.getElementById("h"+id).value=="0"){
        document.getElementById("h"+id).value="1";
        document.getElementById("i"+id).className='shown';
    }
    else{
        document.getElementById("h"+id).value="0";
        document.getElementById("i"+id).className='hidden';
    }
}

and HTML:

<html>
  <head>
    <script src="foo.js">
    </script>
  </head>
  <body>
   <form action="blah blah" > 
    <div class="hidden" id="i0" onclick="to开发者_如何学运维ggle(0);" >
      <!--some image -->
      <input type="hidden" id="h0" name="0" value="0" />
    </div>

    <div class="hidden" id="i1" onclick="toggle(1);" >
      <!--some image -->
      <input type="hidden" id="h1" name="1" value="0" />
    </div>

    <!-- etc -->
   </form>
  </body>
</html>

I know the javascript is properly linked and operational, because when I call the function via chrome's console, it works perfectly and does what I expect. However, when I click this div, it does not work!

What am I doing wrong?


Your divs are hidden initially (class="hidden"), so you won't see anything when you run the page and won't be able to click on them. Also you have typos (there is no onlick event, yet :-)):

onlick="toggle(1);" 

should probably be:

onclick="toggle(1);" 


You must try to lick your element not click, maybe then it will work. Or change onlick to onclick.


Id's cannot start with a number. That is a specification.

Try it like this:

function toggle(id){
    if (document.getElementById(id).value=="0"){
        document.getElementById(id).value="1";
        document.getElementById("i"+id.substr(1)).className='shown';
    }
    else{
        document.getElementById(id).value="0";
        document.getElementById("i"+id.substr(1)).className='hidden';
    }
}

-

<html>
  <head>
    <script src="foo.js">
    </script>
  </head>
  <body>
   <form action="blah blah" > 
    <div class="hidden" id="i0" onclick="toggle('t0');" >
      <!--some image -->
      <input type="hidden" id="t0" name="0" value="0" />
    </div>

    <div class="hidden" id="i1" onclick="toggle('t1');" >
      <!--some image -->
      <input type="hidden" id="t1" name="1" value="0" />
    </div>

    <!-- etc -->
   </form>
  </body>
</html>


You are setting an event on an hidden element i think and thus it doesn't do anything.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜