javascript 单击按钮后加载javascript文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13993748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:24:50  来源:igfitidea点击:

Load javascript file after button click

javascriptjqueryonload

提问by germainelol

I am trying to use a set of textboxes to define some data within my JavaScript file. So in a textbox I enter a Team name "Team name", and the javascript file uses this textbox to store the name of a team in order to print a set of tournament brackets.

我正在尝试使用一组文本框来定义我的 JavaScript 文件中的一些数据。所以在文本框中我输入了一个团队名称“团队名称”,javascript 文件使用这个文本框来存储团队的名称,以便打印一组锦标赛括号。

The javascript file is included in my <head>so it loads before I have actually entered the data in the text boxes. I have this code for a button in the html like so:

javascript 文件包含在我的文件中,<head>因此它在我实际在文本框中输入数据之前加载。我在 html 中有一个按钮的代码,如下所示:

script(type='text/javascript')
    $('#buttontest').click(function() {
        $('div.bracket').show();
        $('div.teamList').hide();
    });

So when the button is pressed, the textboxes are all hidden, and the brackets with the user-defined team names should appear....here is the code at the end of my javascript file:

所以当按钮被按下时,文本框都被隐藏了,带有用户定义的团队名称的括号应该出现......这是我的javascript文件末尾的代码:

$(function() {
    $('#singleElim8').bracket({
        init: singleElim8Data
    })
  $('.bracket').hide();
});

So within div.bracket I have the class #singleElim8 which the javascript uses. But how would I change it so that this javascript to initialize the brackets only runs once the button has been clicked? That way the brackets render AFTER the textboxes have been filled in. Any help appreciated.

所以在 div.bracket 中,我有 JavaScript 使用的 #singleElim8 类。但是我将如何更改它以便初始化括号的 javascript 仅在单击按钮后运行?这样括号在文本框被填充后呈现。任何帮助表示赞赏。

回答by bukart

Just use the getScriptmethod of jQuery

只需使用jQuerygetScript方法

It's very easy to use

使用起来非常简单

$( '#buttontest' ).on( 'click', function() {
    $.getScript( 'url to your js file', function( data, textStatus, jqxhr ) {
        // do some stuff after script is loaded
    } );
} );

回答by Jason Whitted

When you pass a function as the parameter to jQuery it will execute that function during document.ready(). It allows your page to load all of the scripts before executing them.

当您将函数作为参数传递给 jQuery 时,它将在 document.ready() 期间执行该函数。它允许您的页面在执行之前加载所有脚本。

$(function() {
    $('#buttontest').click(function() {
        $('div.bracket').show();
        $('div.teamList').hide();
    });

    $('#singleElim8').bracket({
        init: singleElim8Data
    })
  $('.bracket').hide();
});