简体   繁体   English

外部文件的Javascript函数无法正常工作

[英]Javascript function from external file not working

I'm new to programming and currently learning javascript. 我是编程和学习javascript的新手。 I'm trying to test what I've learned so far using a payroll calculator, but my code is not working. 我正在尝试使用工资单计算器测试到目前为止我学到的东西,但我的代码无效。 I created a function that will be called when the user clicks a button; 我创建了一个在用户点击按钮时调用的函数; if I add the function inside the same HTML file, it works fine. 如果我在同一个HTML文件中添加该函数,它可以正常工作。 When the function is in my external javascript file, the function doesn't work. 当函数在我的外部javascript文件中时,该函数不起作用。 I clicked on View Page Source to confirm the external javascript file was loaded and it was. 我点击了查看页面源以确认外部javascript文件已加载,它是。

HTML CODE HTML代码

<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Payroll Calculator</title>
    <meta name="viewport" contect="width=devide-width, user-    scalable=no,initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/styles.css">
    <link rel="stylesheet" href="css/myStyle.css">
</head>

<body>
    <header>
        <div class="container">
            <div class="col-xs-12">               
                <h1>Payroll Calculator</h1>
            </div>    
        </div>
    </header>

    <div class="container">
        <section class="main row">
            <article class="col-xs-12 col-sm-6 col-md-6">
                <h3>Employee</h3>
                <div class="input-group">
                    <span class="input-group-addon" id="firstName">First Name</span>
                    <input type="text" class="form-control" placeholder="First Name" aria-describedby="basic-addon1">
                </div>
                <br>
                <div class="input-group">
                    <span class="input-group-addon" id="basic-addon1">Last Name</span>
                    <input type="text" class="form-control" placeholder="Last Name" aria-describedby="basic-addon1">
                </div>
                <br>                    
                <div class="input-group">
                    <span class="input-group-addon" id="rate-type">Rate Type&nbsp</span>
                    &nbsp<input type="radio" name="optradio">Hourly 
                    <input type="radio" name="optradio">Salary
                </div>
                <br>
                <div class="input-group">
                    <span class="input-group-addon">Rate Amount</span>
                    <input type="text" class="form-control" aria-label="Amount (to the nearest dollar)">
                    <span class="input-group-addon">.00</span>
                </div>
                <br>

                <label id="EnterHours" onclick="enterHours()">Enter Hours</label>
                <br>
                <p id="hours"></p>
                <br>

                <label id="EnterEarnings">Enter Earnings</label>
                <br>
                <p id="earnings"></p>
                <br>                    

<button type="button" class="btn btn-default"    onclick="enterHours()">Calculate</button>
<button type="button" class="btn btn-default">Cancel</button>


            </article>

            <aside class="col-xs-12 col-sm-6 col-md-6">
                <h3 class="sidebar">Results</h3>
            </aside>
        </section>
    </div>

    <footer>
        <div class="container" >
            <h3>Andres Quintero</h3>
            <p id="demo"></p>
        </div>
    </footer>

<script src="js/app2.js"></script>
</body>

Javascript Code Javascript代码

$(document).ready(function(){

   function enterHours(){
       document.getElementById("hours").innerHTML = "This is a test";    
   }

}

The function is defined in jQuery's scope; 该函数在jQuery的范围内定义; thus, not accessible from the global scope. 因此,无法从全球范围访问。 Move it to global scope; 将其移至全球范围; do not use any wrappers 不要使用任何包装

function enterHours(){
    document.getElementById("hours").innerHTML = "This is a test";    
}

Further reading How do JavaScript closures work? 进一步阅读JavaScript闭包如何工作?

Here's an example of how this works 这是一个如何工作的例子

Defining function in jQuery's scope. 在jQuery的范围内定义函数。 This will fire error: 这会引发错误:

Uncaught ReferenceError: fn is not defined 未捕获的ReferenceError:未定义fn

 $(document).ready(function(){ function fn(){ console.log('Clicked!'); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <button onclick="fn();">Check for fn</button> 

 function fn(){ console.log('Clicked!'); } 
 <button onclick="fn();">Check for fn</button> 

Scope WTF?? 范围WTF ?? What is going on? 到底是怎么回事?

It's about Javascript scope . 这是关于Javascript范围的 If you define a function b inside another function a , b will only be known (and thus, callable ) inside a , but not outside of it. 如果你定义一个function b 的另一个function ab只能是已知的 (因而, 可调用的里面 a ,但不应超出它。

Let's have a look at your code, specifically at the argument you pass to $(document).ready() (which happens to be another function [actually even two: $() and ready() ]): 让我们看看你的代码,特别是你传递给$(document).ready() (恰好是另一个函数[实际上甚至是两个: $()ready() ]):

function() {
   function enterHours(){
       document.getElementById("hours").innerHTML = "This is a test";    
   }
   // enterHours will be known inside the outer function
}
// enterHours will be unknown outside the outer function

The outer function is a so-called anonymous function (it does not have a name), inside which you define a named function called enterHours . 外部函数是一个所谓的匿名函数(它没有名称),在其中定义一个名为 enterHours命名函数。

So what if you want to define a function inside the outer function that is supposed to be "callable from everywhere", which in JS lingo is in the global scope ? 那么如果你想在外部函数中定义一个函数,该函数应该是“可以从任何地方调用的”,这在JS lingo中是否在全局范围内

To make it available everywhere, you have two options. 要使它在任何地方都可用,您有两种选择。 One is, you define your function outside the context of any other function: 一个是,您在任何其他函数的上下文之外定义您的函数:

function enterHours(){
   document.getElementById("hours").innerHTML = "This is a test";    
}

Internally, what is going to happen, is that the browser will attach this function to the so-called "global object" window . 在内部,将要发生的是,浏览器将此功能附加到所谓的“全局对象” window Note that this object does only exist in browsers whereas Javascript can also be run in other contexts like node.js. 请注意,此对象仅存在于浏览器中,而Javascript也可以在其他上下文中运行,如node.js.

If you just enter the above three lines in the browser console of your Chrome browser (accessible in Windows by pressing F12, on Mac OS X bei pressing CMD-ALT-i), you can easily check what I said by typing window. 如果您只是在Chrome浏览器的浏览器控制台中输入上述三行(在Windows中可通过按F12访问,在Mac OS X上按下CMD-ALT-i),您可以通过键入window.轻松查看我说的内容window. . In the completion box you will now find a property on the window object called enterHours . 在完成框中,您将在窗口对象上找到名为enterHours Any property of the window object can either be referenced by calling it explicitly on the window object (like you just did in the console typing window. ) or by simple referencing it without window. 可以通过在window对象上显式调用它来引用窗口对象的任何属性(就像您在控制台键入window.所做的那样),或者通过简单地在没有window.情况下引用它来引用它window. .

So this is the implicit way to define window.enterHours . 所以这是定义window.enterHours隐式方法。

The other option (which you can make use of anywhere in your code) is the explicit attaching of enterHours to the global object: 另一个选项(您可以在代码中的任何位置使用)是将enterHours 显式附加到全局对象:

window.enterHours = function () {
   document.getElementById("hours").innerHTML = "This is a test";    
}

Notice how we moved the name here. 请注意我们如何在此处移动名称。 This creates a property on the window object named enterHours and assigns a reference to an anonymous function to it. 这将在名为enterHours的窗口对象上创建一个属性,并为其分配对匿名函数的引用。 That function will from now on be callable using either window.enterHours(); 从现在开始,该函数可以使用window.enterHours(); or simply enterHours(); 或者只是enterHours(); .

Working solution: 工作方案:

Having read the above explanation you will understand why the following code solves your problem: 阅读上述说明后,您将了解为什么以下代码可以解决您的问题:

$(document).ready(function(){
   window.enterHours = function () {
       document.getElementById("hours").innerHTML = "This is a test";    
   }
}

More on scope in general (regardless of programming language): 更多关于范围(无论编程语言):

https://en.wikipedia.org/wiki/Scope_(computer_science) https://en.wikipedia.org/wiki/Scope_(computer_science)

More on Javascript scope: 有关Javascript范围的更多信息:

http://www.w3schools.com/js/js_scope.asp http://www.w3schools.com/js/js_scope.asp

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

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