简体   繁体   English

Javascript; 如何使函数可以全局访问?

[英]Javascript; how can I make a function globally accessible?

  1. I am trying to learn from this stopwatch example. 我正在尝试从此秒表示例中学习。 I would like to be able to start the stopwatch by clicking on another html element, that is not defined on this page. 我希望能够通过单击此页面上未定义的另一个html元素来启动秒表。

  2. How can I use the 'start' function elsewhere ( eg page reload etc. ) ? 如何在其他地方使用“开始”功能(例如页面重新加载等)?

     var Stopwatch = function(elem, options) { var timer = createTimer(), startButton = createButton("start", start), offset, clock, interval; // append elements elem.appendChild(startButton); reset(); // private functions function createTimer() { return document.createElement("span"); } function createButton(action, handler) { var a = document.createElement("a"); a.href = "#" + action; a.innerHTML = action; a.addEventListener("click", function(event) { handler(); event.preventDefault(); }); return a; } function start() { if (!interval) { offset = Date.now(); interval = setInterval(update, options.delay); } } // public API this.start = start; }; var d = document.getElementById("d-timer"); dTimer = new Stopwatch(d, {delay: 1000}); dTimer.start(); 

Q1: How will I be able to call the start function elsewhere ? 问题1:如何在其他地方调用启动函数? Global ? 全球?

You can assign it to the window scope by doing: 您可以通过执行以下操作将其分配给窗口范围:

window.functionName = function(){
  //your code here
}

If by "not defined on this page" you mean the browser page as in the HTML document, then this is impossible. 如果“未在此页面上定义”是指HTML文档中的浏览器页面,那么这是不可能的。 As soon as you switch the page (or even reload the page) the code will run in a different context. 切换页面(甚至重新加载页面)后,代码将在不同的上下文中运行。

Assuming this is what you want, you could work around this by not actually leaving the page, but instead loading another page and replacing the current pages content. 假设这是您想要的,则可以通过不实际离开页面,而是加载另一个页面并替换当前页面的内容来解决此问题。

If you are not leaving the page, your dTimer object should be globally accessible. 如果不离开页面,则dTimer对象应该是全局可访问的。

The problem was actually a misspelled "id" value. 问题实际上是拼写错误的“ id”值。

Certainly it would be helpful to study javascript in detail, as Matias suggested. 正如Matias建议的那样,详细研究javascript无疑会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM