简体   繁体   中英

Passing reference to object javascript function

I have a function that gets called during a control update where 'This' is passed so the function knows what control is updating. I am also calling the function at page load to get initial values but sending document.getElementById() doesn't seem to work. What should I be passing here?

For example:

    <script type="text/javascript">

    window.onload = function () {
        alert("Got to window.onload");
        materialSelectionChange(document.getElementById('SquaresDropDownList'));

    };


</script>

in the js file...

function materialSelectionChange(obj) {

alert("Got into function");
}

Also, it does fire the js function on change properly

EDIT

The problem seems to be the load time of the JS document. The function wasn't successfully being called at that point because apparently the JS file hadn't finished loading. Likely because of window.onload. It works if I move the function into the page rather than in the JS file. Is there a way I can add delay so I know the page and it's components are fully loaded?

You are not delegating for window load event, you are invoking it, also your missing quotes around the id:

window.onload = myFunction(document.getElementById(typeSelect));

Try wrapping it around:

window.onload = function() {
     myFunction(document.getElementById('typeSelect')); //id in quotes
};

EDIT

You must take care of js file import, import must be first before invoking the function within:

<script src='your-script-file.js'></script>

<script type="text/javascript">
    window.onload = function () {
        materialSelectionChange(document.getElementById('SquaresDropDownList'));
    };
</script>
<select id="typeSelect" onchange="myFunction(this)">

window.onload = function(){
  myFunction.bind(document.getElementById('typeSelect'));
}

The problem seems to be the load time of the JS document. The function wasn't successfully being called at that point because apparently the JS file hadn't finished loading. It works if I move the function into the page rather than in the JS file. Is there a way I can add delay so I know the page and it's components are fully loaded?

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