简体   繁体   English

jQuery / Javascript:在文件外部调用函数

[英]Jquery/Javascript : call a function outside of the file we are calling the function

I have a number of javascript plugins which are included in my HTML file, and are included successfully because I have checked. 我的HTML文件中包含许多javascript插件,由于我已经检查过,因此成功包含了它们。 Heres the problem; 继承人的问题; Basically I want to create a function outside the HTML file, and then inside the HTML file load that particular function when the document is ready. 基本上,我想在HTML文件外部创建一个函数,然后 HTML文件内部创建文档准备就绪时加载该特定函数。

this is the function (outside) of the HTML file. 这是HTML文件的功能(外部)。 As a stand alone JS file: 作为独立的JS文件:

function do_anchor_scrolling() {
    $('#back_to_top').anchorScroll();
    $("#landing_link").anchorScroll();
    $("#menu_link").anchorScroll();
    $("#sauces_link").anchorScroll();
    $("#ranches_link").anchorScroll();
    $("#order_link").anchorScroll();
    $("#about_link").anchorScroll();
    $("#franchise_link").anchorScroll();
});

the function is called do_anchor_scrolling 该函数称为do_anchor_scrolling

How in JQuery can I say when the document is ready perform the do_anchor_scrolling function. 在文档准备好后,我该如何在JQuery中说出do_anchor_scrolling函数。

When the document is ready, call the function. 准备好文档后,调用该函数。

$(document).ready(function(){
    do_anchor_scrolling();
});

Pass it as a handler into the ready method: 将其作为处理程序传递给ready方法:

$(document).ready(do_anchor_scrolling);

Or even shorter: 甚至更短:

$(do_anchor_scrolling);

Notice the function is not executed right there (no invoking parenthesis) - the function object itself is passed into the ready function. 请注意,该函数未在此处执行(没有调用括号)-函数对象本身传递到ready函数中。

You can just do: 您可以这样做:

$.getScript("yourfile.js");//it grabs and executes yourfile.js
                           //so your function is now defined
do_anchor_scrolling();     //and you can call it

You can go without the $_getScript() call by just putting yourfile.js inside a <script> tag in <head> . 您只需将yourfile.js放在<head><script>标记内,而无需$_getScript()调用。

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

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