Call jQuery datepicker from external file

混江龙づ霸主 提交于 2019-12-22 09:45:40

问题


I'm relatively new to jQuery and am having a difficult time getting the jQuery datepicker to work from an external js file.

Originally I created the script as a function, but believed that by doing so I was limiting the scope and it would not be accessible outside the function. I've also tried defining it as a function (and naming the function), then calling it using $(document).ready. I cannot get it to work either way.

My external js script is called scripts.js and its contents are below:

$( "#from" ).datepicker({
    defaultDate: "+1w",
    changeMonth: true,
    changeYear: true,
    numberOfMonths: 2,
    showOn: "both",
    buttonImageOnly: true,
    buttonImage: "images/calendar.gif",
    dateFormat: "mm/dd/yy",
    altField: "#forminp1",
    altFormat: "yyddmm",
    onClose: function( selectedDate ) {
        $( "#to" ).datepicker( "option", "minDate", selectedDate );
    }
});
$( "#to" ).datepicker({
    defaultDate: "+1w",
    changeMonth: true,
    changeYear: true,
    numberOfMonths: 2,
    showOn: "both",
    buttonImageOnly: true,
    buttonImage: "images/calendar.gif",
    dateFormat: "mm/dd/yy",
    altField: "#forminp2",
    altFormat: "yyddmm",
    onClose: function( selectedDate ) {
        $( "#from" ).datepicker( "option", "maxDate", selectedDate );
    },
});

The HTML is:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>jQuery UI Datepicker - Select a Date Range</title>
    <link rel="stylesheet" href="css/jquery-ui-1.10.4.custom.css" type="text/css">
    <script src="js/jquery-1.10.2.js"></script>
    <script src="js/jquery-ui-1.10.4.custom.js"></script>
    <script src="js/scripts.js"></script>

</head>
<body>
    <label for="from">From</label>
    <input type="text" id="from" name="from">
    <label for="to">to</label>
    <input type="text" id="to" name="to">
    <p></p>
     <input type="text" id="forminp1" size="30">&nbsp;<input type="text" id="forminp2" size="30">
</body>
</html>

How can I keep the jQuery code external but have it run properly when the page loads?


回答1:


Wrap the whole file in a jQuery document.ready function like this.

jQuery document ready

The basics are that everything you need to run on page load needs to be inside

$( document ).ready(function(){ ... });

or the shortcut

$( function(){ ... });

See the docs for more info on this.

Script on bottom of page

You could also just put the <script src="..."></script> on the bottom of the page, right above the </body> tag.

This is generally considered to be the best practice way of doing things.



来源:https://stackoverflow.com/questions/22481701/call-jquery-datepicker-from-external-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!