简体   繁体   English

如何为函数添加名称?

[英]How to add a name to a function?

This is probably a really simple question but I am sort of confused how jQuery or JavaScript work in this way. 这可能是一个非常简单的问题,但我对jQuery或JavaScript如何以这种方式感到困惑。

If I have a function for instance like this 如果我有这样的功能

$(function() {
    $('section').on('click', 'div', function(e) {
    var number = Math.floor(Math.random()*videos.length);
    $(this).find('source').each(function(index){ 
          videoSrc = videos[number][index].src;
          $(this).attr('src', videoSrc);
          $('video').load();
          $('video').play();
        });
    });
}); 

How would I write it so that I could reference it to run in html? 我将如何编写它以便引用它以在html中运行?

<body onload="run this function()"> </body>

I see functions written like window.onload=function() or thisFunction = function() etc.. and it sort of has me confused as to how a function is declared when compared to something like HTML where it is literally just div id="name" or class="name" etc.. 我看到像window.onload = function()或thisFunction = function()等这样编写的函数。与HTML之类的函数实际上只是div id =“相比,它使我感到困惑的是如何声明函数名称”或class =“ name”等。

I guess my main question is how would I get the above code to run onload in html instead of on click? 我想我的主要问题是如何获取上述代码以html而不是单击方式在onload上运行? Where do I title a function so that I can use it for later? 我在哪里命名函数,以便以后使用?

Any help on clarifying this would be greatly appreciated! 任何帮助澄清这一点将不胜感激! Cheers! 干杯!

A lot of the answers i've received have ended up making more more confused and I am actually not sure what to do now.. I know I must be over thinking this but I still can't figure out how to get the site to randomize both on click and on page load. 我收到的许多答案最终都变得更加混乱,我实际上不确定现在该怎么办。.我知道我必须对此进行过度思考,但是我仍然不知道如何使该网站正常运行。点击和网页加载随机化。

Here is the code I have currently. 这是我目前拥有的代码。

HTML 的HTML

    <head>
        <title>Randomizer</title>
    </head>

    <body> 

         <section>

          <div>
            <video loop autoplay>
              <source src="" type="">
              <source src="" type="">
              Your browser does not support the <code>video</code> element.
            </video>
          </div> 

        </section>

    </body>

</html>

JavaScript 的JavaScript

var videos = [
    [{type:'mp4', 'src':'/videos/1.webm'}, {type:'webm', 'src':'/videos/1.mp4'}],
    [{type:'mp4', 'src':'/videos/2.webm'}, {type:'webm', 'src':'/videos/2.mp4'}],
    [{type:'mp4', 'src':'/videos/3.webm'}, {type:'webm', 'src':'/videos/3.mp4'}],
    [{type:'mp4', 'src':'/videos/4.webm'}, {type:'webm', 'src':'/videos/4.mp4'}],
    [{type:'mp4', 'src':'/videos/5.webm'}, {type:'webm', 'src':'/videos/5.mp4'}], 

];



$(function() {
    $('section').on('click', 'div', function(e) {
    var number = Math.floor(Math.random()*videos.length);
    $(this).find('source').each(function(index){ 
          videoSrc = videos[number][index].src;
          $(this).attr('src', videoSrc);
          $('video').load();
          $('video').play();
        });
    });
}); 


$(document).ready(function() { 
    var number = Math.floor(Math.random()*videos.length); 
     $(this).find('source').each(function(index){ 
          videoSrc = videos[number][index].src;
          $(this).attr('src', videoSrc);
          $('video').load();
          $('video').play();
        });
 }
);

I was able to finally understand how it works with the above code. 我终于能够理解上面的代码是如何工作的。

Thanks for the help everyone! 感谢大家的帮助!

You don't need a function with a name for what you want to achieve (function names are mostly useful for making stacktraces in debuggers more useful than a list of a dozen (anonymous function) ). 您不需要具有要实现的名称的函数(对于使调试器中的堆栈跟踪比十二个列表(anonymous function)更有用,函数名最有用)。 You need to have a function in a variable. 您需要在变量中具有一个函数。


There are four ways to create a function in JavaScript. 使用JavaScript创建函数的方法有四种。

Function declaration 功能声明

This will create a variable foo in the current scope and assign a named function to it. 这将在当前作用域中创建一个变量foo ,并为其分配一个命名函数。

function foo () {

}

Function declarations are hoisted so it doesn't matter where, in the applicable scope, you put them. 函数声明是悬挂式的,因此在适用范围内的任意位置放置都无关紧要。 It is considered good coding practise to define them before you use them though. 不过,在使用它们之前先定义它们是一种良好的编码习惯。

Anonymous function expression 匿名函数表达式

This will create a function without a name and use it in an expression. 这将创建一个没有名称的函数,并在表达式中使用它。 In this example it is assigned to the variable something . 在这个例子中,它被分配给变量something

something = function () {

};

Named function expression 命名函数表达式

This is the same as an anonymous function expression except that it has a name, creates a variable of that name in the scope of itself and is horribly broken in older versions of Internet Explorer. 这与匿名函数表达式相同,除了它有一个名称,在其自身范围内创建该名称的变量并且在Internet Explorer的较早版本中被严重破坏

something = function foo () {

};

Function constructor 函数构造函数

Do not use function constructors. 不要使用函数构造函数。 They are eval by another name. 它们的别名是eval You can read about them on MDN if you're interested. 如果您有兴趣,可以在MDN上阅读有关它们的信息。


You are currently using an anonymous function expression and passing it as a function argument (instead of assigning it to a variable as the example above does). 您当前正在使用匿名函数表达式并将其作为函数参数传递(而不是像上面的示例那样将其分配给变量)。

Just define the function separately (using any of the above techniques) and then pass the variable instead. 只需单独定义函数(使用上述任何一种技术),然后传递变量即可。

function foo(e) {
    var number = Math.floor(Math.random()*videos.length);
    // etc
}

$('section').on('click', 'div', foo);

Watch out for scope. 注意范围。 Declaring a function inside another function will create a local variable that you can't call globally using an intrinsic event attribute. 在另一个函数中声明一个函数将创建一个局部变量,您不能使用固有事件属性来全局调用该局部变量。

That said, we're approaching two decades since 1997 so you shouldn't be using intrinsic event attributes anyway. 也就是说,自1997年以来我们已经接近二十年,因此您无论如何都不应使用内在事件属性。

$(document).on('load', foo);

Surely 一定

function myname() {
    $('section').on('click', 'div', function(e) {
    var number = Math.floor(Math.random()*videos.length);
    $(this).find('source').each(function(index){ 
          videoSrc = videos[number][index].src;
          $(this).attr('src', videoSrc);
          $('video').load();
          $('video').play();
        });
    });
};

is required 是必须的

Then 然后

myname();

What you have in your code is an anonymous function. 您的代码中有一个匿名函数。 These are useful for one-time calls or for use as callback functions . 这些对于一次性调用或用作回调函数很有用。 For what you are trying to accomplish, you want to assign the FUNCTION REFERENCE to a variable. 对于您要完成的工作,您想将FUNCTION REFERENCE分配给变量。 A function reference can be INVOKED at a later time by using parentheses, eg var_name() 以后可以使用括号来调用函数引用,例如var_name()

var x = function(){
  // your code
}

onclick="x()"

It would look like this: 它看起来像这样:

$(function() {
    function myFunction() {
        $('section').on('click', 'div', function(e) {
            ...
        });
    }

    $('body').on('load', function() {
        myFunction();
    });
});

Placing the onload listener in the script like this is preferable for several reasons, such as separation of concerns, cleaner markup, etc. 最好将这样的onload侦听器放置在脚本中,原因有几个,例如关注点分离,更清晰的标记等。

That said, your original code does the same job without the body onload property. 就是说,原始代码没有body onload属性就可以完成相同的工作。 You don't actually need either method. 您实际上不需要任何一种方法。

To name the function you can write 要命名的功能,你可以写

function function_name(){
    $('section').on('click', 'div', function(e) {
    var number = Math.floor(Math.random()*videos.length);
    $(this).find('source').each(function(index){ 
          videoSrc = videos[number][index].src;
          $(this).attr('src', videoSrc);
          $('video').load();
          $('video').play();
        });
    });
};

Then you call it as function_name(); 然后将其称为function_name();

To make it run when the html is ready you write 要使其在html准备就绪时运行,请编写

$( document ).ready(
    function_name();
});

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

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