javascript - JavaScript 中带有动态参数的动态 onclick 函数分配?

标签 javascript html

我有这个代码:

document.getElementById('img'+i).onclick = function(){popup_show('popup',array_msg[i]+'|||'+date('Y-m-d',strtotime(lec_date))+'-==-'+str_view_forConflict, 'AddEditSchedule;;popup_drag2;;EditSched;;'+String(array_msg_id[3])+';;view', 'popup_drag', 'popup_exit', 'screen-center', 0, 0);};

...但是当我点击图像时,array_msg[i] 的数据是循环的最后一个数据,这意味着索引是循环的长度。为此,我使用 IE。

请给我一个关于如何做到这一点的想法。在 FF 中,它工作正常,因为我使用 setAttribute

@bobince

document.getElementById('img'+i).onclick= popup_show.bind(window, 'popup',array_msg[i]+'|||'+date('Y-m-d',strtotime(lec_date))+'-==-'+str_view_forConflict,'AddEditSchedule;;popup_drag2;;EditSched;;'+array_msg_id[3]+';;view','popup_drag', 'popup_exit', 'screen-center', 0, 0    ); 
                if (!('bind' in Function.prototype)) {
                    Function.prototype.bind= function(owner) {
                        var that= this;
                        var args= Array.prototype.slice.call(arguments, 1);
                        return function() {
                            return that.apply(owner,
                                args.length===0? arguments : arguments.length===0? args :
                                args.concat(Array.prototype.slice.call(arguments, 0))
                            );
                        };
                    };
                }

最佳答案

Treby,这是您答案的清理版本。您添加的附加匿名函数不是必需的。

for (var i = 0, l = array.length; i < l; i++ ) {
  document.getElementById(i + '05').onclick = (function(tmp) {
    return function() { 
      popup_show(
        "popup", 
        array_msg[tmp] + '|||' + date('Y-m-d', strtotime(lec_date)) + '-==-' + str_view_forConflict, 
        "AddEditSchedule;;popup_drag2;;EditSched;;" + String(array_msg_id[3]) + ";;view", 
        "popup_drag", "popup_exit", "screen-center", 0, 0
      );
    };
  })(i);
}

编辑以修复关闭问题

关于javascript - JavaScript 中带有动态参数的动态 onclick 函数分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2025836/

相关文章:

javascript - 如何在 React Native 中存储状态值?

javascript - 如何从外部 sagas.js 调用 saga?

html - 如何在表格单元格 "height: 100%"内创建一个 div

html - Bootstrap 4 位置重叠和尺寸问题

javascript - 如何随时间改变背景不透明度?

Javascript Date 对象奇怪的行为/错误?

javascript - 在不知道替换的 id 或 src 的情况下更改 img 标签的 src

javascript - jquery 显示更多行但不是全部

html - 同一个浏览器在不同电脑上显示不同

javascript - 触发事件(jQuery)后如何恢复为 HTML/DOM 中的默认值?