简体   繁体   中英

JavaScript method does not execute fully when called from (document).ready

I've got a page which shows (html output from asp.net code behind) houses/properties. I've constructed the following javascript which, on the push of a button, changes all the css classes on the properties so the html does not change, but the css class does, to get a 2 column view.

This works fine. But then I was figuring, if the users picks the 2 column view, and navigates to the next page (it's sort of a paged list), the view is reset back to the original (begin 1 column).

So I've done the following. If the users clicks the button, and goes from 1 columnview, to 2 columnview, I save that value in window.name as 1 or 2.

Afterwards I buil this little script here:

 $(document).ready(setView());

 function setView() {
     if (window.name != null) {
         if (window.name == 2) {
             window.Show2Cols();
         }
         if (window.name == 1) {
             window.Show1Col();
         }

     }
 }

This works. The method Show2Cols() begins as following:

 function Show2Cols() {

 alert("Show2Cols is executed");
     var nodes = document.getElementById("panden").getElementsByTagName("div");
     alert("Just got all nodes.");
     for (i = 0; i < nodes.length; i++) 
     {....

So, when I change the page, it pop's up saying "Show2Cols is executed", but it does not say "just got all nodes".

As this is my first JS ever, and it's not gonna get more complicated, I'd like to ask you guys where the problem exists?

My guess is that on (document).ready() works, but then the .getElementById() methods don't work yet, as there is nothing on the page yet (visually).

Thanks in advance.

The problem is your reference to your function

$(document).ready(setView());

You are executing the function and returning its value as the DOM ready event handler,here is what you need

$(document).ready(setView);

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