开发者

Jquery "hide on load" causing a Javascript error

开发者 https://www.devze.com 2023-01-22 03:38 出处:网络
I am trying to write a menu whose subitems vanish when the page is loaded. If you need full HTML, I will copy it, however it just consists of a bunch of DIVs, the items under the headers have a class

I am trying to write a menu whose subitems vanish when the page is loaded.

If you need full HTML, I will copy it, however it just consists of a bunch of DIVs, the items under the headers have a class of subitems.

I have managed to do what I need via:

   $(document).ready(

    $(".subitems").hide()

   );

However, in Chrome, despite it working fine, I get the following error in the console:

Jquery "hide on load" causing a Javascript error

(Using picture as I can't copy the formatting well)

When I remove the above code, the error goes. I guess I have done something wrong, but I can't see it and so far it wo开发者_JAVA百科rks in every browser I have tested.

Any suggestions on either:

  1. Have I done something wrong?
  2. Is there a better way to achieve what I want?


You're missing the anonymous function(function() { }) wrapper, like this:

$(document).ready(function() {
 $(".subitems").hide();
});

It's trying to do $(".subitems").hide().call() under the covers when it executes the ready handlers...but this isn't a function. Instead, it's executing immediately (not on document.ready) and throwing an error when document.ready tries to run the result of .hide().

Just to note, there's a shorter form of the above as well:

$(function() {
 $(".subitems").hide();
});


As the error is solved, maybe there is another way to do it.
I guess you did'nt really want to hide on page-load, but want to hide if javascript is active(you use ready to have access to the objects). If I'm right, there is an easier way. Give the <html> a class

$('html').addClass('scripted')

(as <html> is known everytime/everywhere, you already can do this inside the <head>)

...then you will be able to hide the objects via css and don't have to wait for ready()

html.scripted .subitems{display:none}/*only hidden if js is off*/
0

精彩评论

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