简体   繁体   中英

function inside window.onload

I have an external js file that contains window.onload at top. I want to call control.next() function inside window.onload when I click the button that is in a separate HTML file.

window.onload = function() {

 control = {

    margin: function(n) {
        sliderContent.style.marginLeft = '-' + n + '00%';
    },

    prev: function() {
        (n === 0) ? n = (slideCount - 1) : n--;
        control.margin(n);
    },

    next: function() {
        alert("next");
        (n < slideCount - 1) ? n++ : n = 0;
        control.margin(n);
    },

    slide: function() {
        move = setInterval(function(){
            (n < slideCount - 1) ? n++ : n = 0;
            control.margin(n);
        }, 4000)
    }
 }

}

Button code is:

<button class="xy" onclick="">next</button>

you can also check fiddle at http://jsfiddle.net/gLPhr/2/

What you are trying to do is not possible since the control s scope is inside the anonymouys function. I dont see a that you need the onload event, remove it and your code should work fine.

You just need to expose the control object, yes?

var control;

window.onload = function() {

 control = {
...

Otherwise, control is scoped to window.onload , and nothing outside can see it.

Btw, not sure that fiddle is where you want it.

Keep the control variable external, and just call the method you need in the onload handler.

var control = {

 margin: function(n) { sliderContent.style.marginLeft = '-' + n + '00%'; }, prev: function() { (n === 0) ? n = (slideCount - 1) : n--; control.margin(n); }, next: function() { alert("next"); (n < slideCount - 1) ? n++ : n = 0; control.margin(n); }, slide: function() { move = setInterval(function(){ (n < slideCount - 1) ? n++ : n = 0; control.margin(n); }, 4000) } 

}

window.onload = control.next

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