简体   繁体   中英

JScript Runtime Error in ASP.net MVC 3 after placing the javascript in a separate JS File

Hi I've got this Javascript Runtime Error in ASP.net MVC3. The code fragment below works just fine but the problem here goes when I try to place the displayTime() into another .js file.... I tried placing the whole javascript function in a separate js file then adding another import like these:

<script src="@Url.Content("~/Scripts/customFunction.js")" type="text/javascript"></script>

right after the script Ive imported... all of this codes are placed in my _Layout.cshtml file. But unfortunate a MS JScript Runtime Error Occured in the <body onload="displayTime()"> saying Object Expected.... :( Hope someone can help

<body onload="displayTime()">
        <!-- scripts -->
        <script src="@Url.Content("~/Scripts/jquery-1.7.2.min.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>
        <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
        <script type="text/javascript">

        function displayTime()
        {

        }
    </script>
    </body>

Here is the full code of the JS Function:

var serverTime = @DateTime.Now.TimeOfDay.TotalSeconds;
var serverOffset = serverTime - getClientTime();

function getClientTime()
{
    var time = new Date();

    return (time.getHours() * 60 * 60) +
        (time.getMinutes() * 60) + (time.getSeconds());
}

function displayTime()
{
    var serverTime = getClientTime() + serverOffset;
    var hours = Math.floor(serverTime / 60 / 60).toString();
    var minutes = Math.floor(serverTime / 60 % (hours * 60)).toString();
    var seconds = Math.floor(serverTime % 60).toString();

    hours = hours.length == 1 ? '0'+ hours : hours;
    minutes = minutes.length == 1 ? '0'+ minutes : minutes;
    seconds = seconds.length == 1 ? '0'+ seconds : seconds;

    document.getElementById("clock").innerHTML = hours + ":" +
        minutes + ":" + seconds; // <-- updates the "clock" div.

    setTimeout(displayTime, 1000); // <-- calls this function again in 1 second.
}
<head>
<script type="text/javascript">
var serverTime = @DateTime.Now.TimeOfDay.TotalSeconds;
</script>
<script src="@Url.Content("~/Scripts/customFunction.js")" type="text/javascript"></script>
</head>

<body onload="displayTime()">
</body>

The script containing this displayTime function should be placed in your <head> section. Alternatively since you are using jQuery, why don't you simply use the $(document).ready function?

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