简体   繁体   中英

How to Minimize the Code of JavaScript In DatePicker

I am Using jQuery date picker,and I have created multiple instances of DatePicker ( an example )

In JavaScript this script is used four time:

$( "#datepicker" ).datepicker({
    showOn: "button",
    buttonImage:"images/calendar.gif",
    buttonImageOnly: true });

I want to minimize the code of javascript. What should I do?

You can select all ids together:

$( "#datepicker, #datepicker2, #datepicker3, #datepicker4" ).datepicker({
    ...

Although, personally I would've introduced class my-datepicker and used it:

$(".my-datepicker").datepicker({

You could give each of the input elements same class say myDatepicker and then try

Here is the HTML

<p>Date: <input type="text" id="datepicker" class="myDatepicker"></p>
<p>Date: <input type="text" id="datepicker2" class="myDatepicker"></p>
<p>Date: <input type="text" id="datepicker3" class="myDatepicker"></p>
<p>Date: <input type="text" id="datepicker4" class="myDatepicker"></p>

and javascript

        $( ".myDatepicker" ).datepicker({ showOn: "button",

          buttonImage:"images/calendar.gif",

          buttonImageOnly: true 
         });

and here try the fiddle

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