将两个Javascript函数组合到一个window.onload无法正常工作

时间:2016-03-26 10:41:36

标签: javascript

我想在window.onload事件上运行两个函数,但到目前为止只有最后一个函数似乎有效。一个功能用于图像滑块,另一个功能用于从Google电子表格单元格中检索数据。

function fun1() { //image slider

  var ul;
  var li_items;
  var imageNumber;
  var imageWidth;
  var prev, next;
  var currentPostion = 0;
  var currentImage = 0;

  function init() {
    ul = document.getElementById('image_slider');
    li_items = ul.children;
    imageNumber = li_items.length;
    imageWidth = li_items[0].children[0].clientWidth;
    ul.style.width = parseInt(imageWidth * imageNumber) + 'px';
    prev = document.getElementById("prev");
    next = document.getElementById("next");

    prev.onclick = function() {
      onClickPrev();
    };
    next.onclick = function() {
      onClickNext();
    };
  }

  function animate(opts) {
    var start = new Date;
    var id = setInterval(function() {
      var timePassed = new Date - start;
      var progress = timePassed / opts.duration;
      if (progress > 1) {
        progress = 1;
      }
      var delta = opts.delta(progress);
      opts.step(delta);
      if (progress == 1) {
        clearInterval(id);
        opts.callback();
      }
    }, opts.delay || 17);

  }

  function slideTo(imageToGo) {
    var direction;
    var numOfImageToGo = Math.abs(imageToGo - currentImage);


    direction = currentImage > imageToGo ? 1 : -1;
    currentPostion = -1 * currentImage * imageWidth;
    var opts = {
      duration: 1000,
      delta: function(p) {
        return p;
      },
      step: function(delta) {
        ul.style.left = parseInt(currentPostion + direction * delta * imageWidth * numOfImageToGo) + 'px';
      },
      callback: function() {
        currentImage = imageToGo;
      }
    };
    animate(opts);
  }

  function onClickPrev() {
    if (currentImage == 0) {
      slideTo(imageNumber - 1);
    } else {
      slideTo(currentImage - 1);
    }
  }

  function onClickNext() {
    if (currentImage == imageNumber - 1) {
      slideTo(0);
    } else {
      slideTo(currentImage + 1);
    }
  }

}

function fun2() {
  // Google spreadsheet js

  google.load('visualization', '1', {
    callback: function() {

      var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1sA7M5kG6Xo8YScD1Df38PIA_G0bvhGRdqoExXg0KJTs/gviz/tq?tqx=out:html&tq?gid=0&headers=0&range=A1:C');
      query.send(displayData);
    }
  });

  function displayData(response) {

    numRows = response.getDataTable().getValue(0, 0);

    document.getElementById('data').innerHTML = numRows;
  }
}


var addFunctionOnWindowLoad = function(callback) {
  if (window.addEventListener) {
    window.addEventListener('load', callback, false);
  } else {
    window.attachEvent('onload', callback);
  }
}

addFunctionOnWindowLoad(fun1);
addFunctionOnWindowLoad(fun2);

这是我尝试link的答案,但我似乎无法弄清楚我哪里出错了。

2 个答案:

答案 0 :(得分:1)

这就是我最终做的,现在所有的功能都有效。

var ul;
var li_items;
var imageNumber;
var imageWidth;
var prev, next;
var currentPostion = 0;
var currentImage = 0;


function init() {
    ul = document.getElementById('image_slider');
    li_items = ul.children;
    imageNumber = li_items.length;
    imageWidth = li_items[0].children[0].clientWidth;
    ul.style.width = parseInt(imageWidth * imageNumber) + 'px';
    prev = document.getElementById("prev");
    next = document.getElementById("next");
        prev.onclick = function() {
        onClickPrev();
    };
    next.onclick = function() {
        onClickNext();
    };
}

function animate(opts) {
    var start = (new Date());
    var id = setInterval(function() {
        var timePassed = (new Date()) - start;
        var progress = timePassed / opts.duration;
        if (progress > 1) {
            progress = 1;
        }
        var delta = opts.delta(progress);
        opts.step(delta);
        if (progress == 1) {
            clearInterval(id);
            opts.callback();
        }
    }, opts.delay || 17);
    //return id;
}

function slideTo(imageToGo) {
    var direction;
    var numOfImageToGo = Math.abs(imageToGo - currentImage);
    // slide toward left

    direction = currentImage > imageToGo ? 1 : -1;
    currentPostion = -1 * currentImage * imageWidth;
    var opts = {
        duration: 1000,
        delta: function(p) {
            return p;
        },
        step: function(delta) {
            ul.style.left = parseInt(currentPostion + direction * delta * imageWidth * numOfImageToGo) + 'px';
        },
        callback: function() {
            currentImage = imageToGo;
        }
    };
    animate(opts);
}

function onClickPrev() {
    if (currentImage === 0) {
        slideTo(imageNumber - 1);
    } else {
        slideTo(currentImage - 1);
    }
}

function onClickNext() {
    if (currentImage == imageNumber - 1) {
        slideTo(0);
    } else {
        slideTo(currentImage + 1);
    }
}

window.onload = init;


function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

function fun2() {
    // Google spreadsheet js

    google.load('visualization', '1', {
        callback: function() {

            var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1sA7M5kG6Xo8YScD1Df38PIA_G0bvhGRdqoExXg0KJTs/gviz/tq?tqx=out:html&tq?gid=0&headers=0&range=A1:C');
            query.send(displayData);
        }
    });

    function displayData(response) {

        numRows = response.getDataTable().getValue(0, 0);

        document.getElementById('data').innerHTML = numRows;
    }


}
addLoadEvent(fun2);
addLoadEvent(function() {
});

答案 1 :(得分:0)

我不久前发现了这个功能,不管你信不信,我仍然需要经常使用它。 addEventLoad() 只需在传递要加载的功能时调用addEventLoad

  

“它的工作方式相对简单:如果window.onload尚未分配一个函数,传递给addLoadEvent的函数只是分配给window.onload。如果已经设置了window.onload,那么一个全新的函数创建后,首先调用原始的onload处理程序,然后调用新的处理程序。“

此代码段将在window.onload

上加载3个功能

<强>段

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}


function alert1() {
  alert("First Function Loaded");
}

function alert2() {
  alert("Second Function Loaded");
}

function alert3(str) {
  alert("Third Function Loaded; Msg: " + str);
}
addLoadEvent(alert1);
addLoadEvent(alert2);
addLoadEvent(function() {
  alert3("This works");
});
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>