简体   繁体   中英

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.

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. 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.

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. 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.

<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(){ ... }); 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:

<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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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