如何在javascript中推广函数

时间:2011-06-03 13:11:37

标签: javascript javascript-events event-handling yui yui-calendar

我有来自日期和日期文本框,当我选择文本框旁边的图标时,将显示日历,当我选择日期时,日期将显示在相应的文本框中。 我的目的是为toDate和fromDates使用单一的通用函数。我可以这样做,我使用的是YUI Calender,这是我的代码。

<td>
    <strong>From Date</strong>
</td>
<td>
    <input type="text" name="fromDate" id="fromDate" value="" size=15>
    <img id="calendarFromIcon" src="${resource(dir: "images",    file: "calendar_icon.jpg")}" />
    <div  id="calendarFromContainer"></div>
</td>
<td>
    <strong>To Date</strong>
</td>
<td>
    <input type="text" name="toDate" id="toDate" value="" size=15>
    <img id="calendarToIcon" src="${resource(dir: "images", file: "calendar_icon.jpg")}" />
    <div  id="calendarToContainer"></div>
</td>

,这个脚本是

var myFromCalendar = new YAHOO.widget.Calendar("calendarFromContainer", {
    close: true,
    navigator: true
});

myFromCalendar.render();
myFromCalendar.hide();

function handleSelect(type, args, obj) {
    var dates = args[0];
    var date = dates[0];
    var year = date[0];

    month = date[1];
    month = (month < 10) ? "0" + month : month;

    day = date[2];
    day = (day < 10) ? "0" + day : day;

    var txtDate1 = document.getElementById("fromDate");
    txtDate1.value = year+ "/"+ month + "/" + day;
    myFromCalendar.hide();
}

myFromCalendar.selectEvent.subscribe(handleSelect,myFromCalendar, true);

YAHOO.util.Event.addListener("calendarFromIcon", "click", function(e) {
    var calContainer = YAHOO.util.Dom.get("calendarFromContainer");

    var selectedDate = document.getElementById("fromDate");
    if (selectedDate.value) {
        var matches = selectedDate.value.match(/^\s*0?(\d+)\/0?(\d+)\/(\d+)\s*$/);
        var year = parseInt(matches[3]);
        var month = parseInt(matches[1]);
        var pageDate = month+"/"+year;

        myFromCalendar.cfg.setProperty("pagedate", pageDate, false);
        myFromCalendar.cfg.setProperty("selected", selectedDate.value, false);
        myFromCalendar.render();
     }

     myFromCalendar.show();
});

1 个答案:

答案 0 :(得分:0)

您可以使用jquery将单个函数应用于多个HTML元素。 Jqueries select函数可以帮助您。