简体   繁体   English

在单独的文件中放一些Javascript?

[英]Putting a bit of Javascript in a separate file?

I'm trying to re-create this locally: http://jsfiddle.net/janpetras/wzBu8/ Granted, it shouldn't be that complicated, but I can't get it to work. 我正在尝试在本地重新创建它: http : //jsfiddle.net/janpetras/wzBu8/当然,它不应该那么复杂,但是我无法使其正常工作。

This is the code: 这是代码:

$(function(){
    var moneyEarned,yearlySalary,secondSalary;
    $("#startEarning").click(function(){
        moneyEarned = 0;
        var hourlySalary = $("#hourlySalary").val();
        if(hourlySalary.length > 0) {
            secondSalary = hourlySalary / 3600;
        } else {
            yearlySalary = $("#yearlySalary").val(); 
            secondSalary = yearlySalary / 7200000;
        }

        setInterval(updateMoneyEarned, 1000);
    });


    function updateMoneyEarned() {
        moneyEarned += secondSalary;
        $("#moneyEarned").html(accounting.formatMoney(moneyEarned));
    }
});

I want to put the Javascript code into a separate "script.js" file. 我想将Javascript代码放入一个单独的“ script.js”文件中。 I made the file, correctly linked to it in the HTML, I included jQuery and the accounting.js and everything, and it's not working, not updating. 我制作了文件,并正确地将其链接到HTML中,包括jQuery和accounting.js以及所有内容,但它不起作用,也没有更新。

I tried putting the code straight into the HTML and it's working if I do that, so clearly the problem is the way I make the script.js. 我尝试将代码直接放入HTML中,如果这样做就可以正常工作,因此很显然问题出在我编写script.js的方式上。 I just copied/pasted that code, is there more to it? 我只是复制/粘贴了该代码,还有更多内容吗? What am I doing wrong? 我究竟做错了什么?

Remember that you have to do things in order. 请记住,您必须按顺序做事。 You can't include this file if you didn't include jQuery before. 如果您之前未包含jQuery,则无法包含此文件。

<html>
    <head>
        <title>...</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        <script type="text/javascript" src="path/to/your/script.js"></script>
    </head>
    <body>
        <!-- your content -->
    </body>
</html>

After you have the correct order, you will be able to execute your scripts. 正确顺序后,您将能够执行脚本。 If your $(function(){ ... }); 如果您的$(function(){ ... }); call doesn't work, try using it this way: 呼叫无效,请尝试通过以下方式使用它:

$(document).ready(function() {
    // Your code here
});

and see if it works. 看看是否可行。

In your jsfiddle i can see that you were including accounting.js in css section: 在您的jsfiddle中,我可以看到您在css部分中包含了accounting.js:

<script src="//cdn.jsdelivr.net/accounting.js/0.3.2/accounting.min.js"></script>

I moved it to the html section and it started working. 我将其移至html部分,并开始工作。

http://jsfiddle.net/GvAzM/1/ http://jsfiddle.net/GvAzM/1/

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

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