使用Javascript通过ajax回调更新DOM

时间:2015-03-26 00:23:57

标签: javascript ajax dom dynamic scope

我正在制作一个允许用户在指定日期存储活动的日历。当我每个新月更新日历时,我会创建新节点并为它们分配一个ID,这样我就可以稍后向它们添加内容:

 var i = 1;
  for(var w in weeks){
    var days = weeks[w].getDates();
    // days contains normal JavaScript Date objects.

   // alert("Week starting on "+days[0]);
    var which_week = "week"+i;
    i++;
    for(var d in days){     
      console.log(days[d].toISOString());
      var tr = document.getElementById(which_week);
      if(days[d].getMonth()==month){

        var newDay = document.createElement("div");
        newDay.appendChild(document.createTextNode(days[d].getDate()));
        //alert(newDay.data);
        newDay.setAttribute("id", newDay.lastChild.data);
        $(tr).append('<td><a class="linky" href="#">'+newDay.lastChild.data+'</a></td>');
      }
      else{
        $(tr).append('<td class="disabledCell"><a class="linky disabledLink" href="#">'+days[d].getDate()+'</a></td>');
      }
    }
  }
  getEvents();
}

我修改节点:

function ajaxEventCallback(event){
  var data = event.target.responseText;
  data = JSON.parse(event.target.responseText);
  for  (var i = 0; i < data.length; i++) 
    //alert("event: " + data[i].title);
    //
    var dayOfEvent= data[i].day;
    document.getElementById(dayOfEvent).appendChild(data[i].title);

}

我在最后一行代码中遇到“无法读取属性追加null的子句”错误。我认为这是一个范围问题,但我不知道从哪里开始解决它。

1 个答案:

答案 0 :(得分:0)

在全球范围内:

var allWeeks = [];

在第一个函数中:

var i = 1;
for(var w in weeks){
    var days = weeks[w].getDates();
    // days contains normal JavaScript Date objects.

    // week object used to store the days until it is added to the array
    var week = [];

    var which_week = "week"+i;
    i++;
    for(var d in days){     
        console.log(days[d].toISOString());
        var tr = document.getElementById(which_week);
        if(days[d].getMonth()==month){

            // add the day to the temporary week object
            week.push(days[d].getDate());

            $(tr).append('<td><a class="linky" href="#">' + days[d].getDate() + '</a></td>');
        }
        else{
            $(tr).append('<td class="disabledCell"><a class="linky disabledLink" href="#">'+days[d].getDate()+'</a></td>');
        }

    }

    // add the temporary week array to the array of weeks
    allWeeks.push(week);
}

在ajax事件中:

function ajaxEventCallback(event){
    var data = event.target.responseText;
    data = JSON.parse(event.target.responseText);

    for  (var i = 0; i < data.length; i++) {
        var dayOfEvent = data[i].day;
        // Here you add the event to the appropriate day in the array
    }
}