简体   繁体   English

如何在Javascript global中创建一个函数到我的html

[英]How can I make a function in Javascript global to my html

First, I appreciate any direction given.... Let me preface this by saying, I am learning Javascript and HTML. 首先,我欣赏任何给出的方向......让我先说一下,我正在学习Javascript和HTML。

My problem is that I am trying to call my function to update audio time like so: 我的问题是我试图调用我的函数来更新音频时间,如下所示:

<audio id="track" preload="auto" type="audio/mpeg" ontimeupdate="displayTime(this)">
            <source src="mp3/mysong.mp3" type="audio/mpeg">
            Unsupported audio format!
        </audio>

My function is in the Javascript IFFE function: 我的函数在Javascript IFFE函数中:

$(document).ready(function () {
 ... /*Global Variables*/

 ...

 function displayTime(event) {

            sec = Math.floor(event.duration);
            min = Math.floor(sec / 60);
            min = min >= 10 ? min : '0' + min;
            sec = Math.floor(sec % 60);
            sec = sec >= 10 ? sec : '0' + sec;


            ct_sec = Math.floor(event.currentTime);
            ct_min = Math.floor(ct_sec / 60);
            ct_min = ct_min >= 10 ? ct_min : '0' + ct_min;
            ct_sec = Math.floor(ct_sec % 60);
            ct_sec = ct_sec >= 10 ? ct_sec : '0' + ct_sec;


            document.getElementById('ticker').innerHTML = ct_min + ":" + ct_sec + "-" + min + ":" + sec;

        }



});

Can anyone advise on why I get the error function displayTime(this) not defined? 任何人都可以建议我为什么得到错误函数displayTime(this)没有定义? I also tried using window.myFunction to try to make it global to the dom ... to no avail. 我也尝试使用window.myFunction试图让它全局到dom ......无济于事。

because it's not visible outside the scope of the function. 因为它在函数范围之外是不可见的。

After the declaration assign the reference of the function to the global object 声明后,将函数的引用分配给全局对象

window.displayTime = displayTime;

Anything in the document.ready handler will be put inside of that function's scope. document.ready处理程序中的任何内容都将放在该函数的范围内。 Thus, if you want the function to be declared global from within the scope, you need to declare it in the global scope, and then you may use it with the window. 因此,如果要在范围内将函数声明为全局,则需要在全局范围内声明它,然后可以将其与window.一起使用window. prefix. 字首。

$(document).ready(function () {
 ... /*Global Variables*/
window.displayTime = function (event) { ... }
});

Usage: 用法:

<button onclick="window.displayTime()">test</button>

除了使函数成为全局函数之外,您还可以通过JavaScript附加事件侦听器,如下所示:

$('#track').on('timeupdate', displayTime);

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

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