繁体   English   中英

将功能绑定到由javascript创建的元素

[英]bind function to an element that created by javascript

我想使用javascript创建日历:

我通过此功能创建元素:

createElem : function (name, attrs){
     var el = document.createElement(name);
     for(var key in attrs) {
        el.setAttribute(key, attrs[key]);
     }
     return el;
}

表:

var tb=this.createElem("table", {"class":"p-calendar", id: "p-calendar"});

行和单元格:

for(var i=2; i<to; i++){
    tb.insertRow(i);
    for(var j=0; j < 7; j++){
       tb.rows[i].insertCell(j);
       .
       .

所以在我的循环中:

tb.rows[i].cells[j].className="day"; // it's work

但是:

tb.rows[i].cells[j].onclick = function(){
    tb.rows[i].cells[j].id = "today";
}  // Unable to set property 'id' of undefined or null reference 
  1. 为什么会出错?!
  2. 将功能绑定到由javascript创建的元素的最佳方法是什么?

提前致谢。

简短的答案:您需要closure onclick处理程序。

长答案:您的索引ijfor循环中递增。 当您实际单击该元素时,稍后将调用onclick处理程序。 猜猜ij的值是多少。 它们超出了rowscells的元素数组的范围。 这意味着每个元素都使用相同的ij值,而且没有一个在元素数组的范围内获取值。 您可以通过在当前onclick处理程序中记录ij的值来验证这一点。

解:

更换块:

tb.rows[i].cells[j].onclick = function(){ ... }

与:

var getOnclickMethod = function (i, j) {
    var cur_i = i * 1;
    var cur_j = j * 1;
    var callback = function(){
        tb.rows[cur_i].cells[cur_j].id = "today";
    };
    return callback;
};

tb.rows[i].cells[j].onclick = getOnclickMethod(i, j);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM