0

我的约会有一个小问题。我有一个接收日期并存储到几个变量中的函数。我将传入的日期设置为两个变量的不同日期,但是运行时是相同的。以下是一个片段

function dateChange(dateInput){
var prevWeek = dateInput; 
var prevMonth = dateInput;
prevWeek.setDate(prevWeek.getDate()-7);
prevMonth.setDate(prevMonth.getDate()-30); 

 var $prev_month_link = $( '<a>' )
      .html( "month" )
      .click(function(event){
          //prevMonth = new Date();
          alert("click prevMonth: "+prevMonth);
        //dateChange( prevMonth ) 
        prevMonth = prevMonth.substring(3,5)+"/"+prevMonth.substring(0,2)+"/"+prevMonth.substring(6,10)
        var prevMonth2 = new Date(prevMonth);
        //alert("line 132, current2 is: "+prevMonth2);
        dateChange(prevMonth2);
        event.stopPropagation();
      })
      .addClass("prevMonth")
      .attr('data-name', prevMonth)
      .appendTo( $prev_container )

      var $prev_week_link = $( '<a>' )
      .html( "week" )
      .click(function(event){
          alert("click prevWeek: "+prevWeek);
        prevWeek = prevWeek.substring(3,5)+"/"+prevWeek.substring(0,2)+"/"+prevWeek.substring(6,10)
        var prevWeek2 = new Date(prevWeek);
        dateChange( prevWeek2 ) 
        event.stopPropagation();
      })
      .addClass("prevWeek")
      .attr('data-name', prevWeek)
      .appendTo( $prev_container )
}

我的问题是 prevWeek 和 prevMonth 有相同的日期,即使我设置它们不同。我不确定是不是因为发生了点击事件。例如,您可以在这里看到http://www.ccy.com.au/availability/

先感谢您

4

1 回答 1

3

您可能认为这两行复制dateInputprevWeekand prevMonth

var prevWeek = dateInput; 
var prevMonth = dateInput;

不是这样。他们制作prevWeekprevMonth指向同一个地方。然后当您在它们上调用方法时:

prevWeek.setDate(prevWeek.getDate()-7);
prevMonth.setDate(prevMonth.getDate()-30); 

您只是在更改他们指向的对象;相当于

dateInput.setDate(dateInput.getDate()-7);
dateInput.setDate(dateInput.getDate()-30); 

Probably not what you wanted. To actually copy the date, use new Date, passing it the date you want to copy:

var prevWeek = new Date(dateInput); 
var prevMonth = new Date(dateInput);

This makes them each point to a new, non-identical Date representing the same moment in time.

于 2013-07-26T04:17:47.537 回答