为什么撤消此function?

我有一个包含大量数据的HTML表。 可以单击某些单元格,当它们执行时,其内容将被编辑界面替换,其中包括取消按钮。

单击取消按钮时,将运行以下Javascript(带有一些jQuery):

function undo_changes(el) { // Restore the previously-stored original innerHTML and event handler el.innerHTML = cell_contents; cell_contents = undefined; $(el).bind('click', box_click); // Restore the form's action and events $(main_form).attr('action',main_form_destination).attr('onchange', 'return true'); } 

取消按钮实现如下( this.parentNode指的是单元格):

  

单击取消按钮时,似乎没有任何更改。 当我逐步调试调试器中的代码时,更改按预期发生。 但是,在到达function结束时,突然恢复所有更改。 这是怎么回事?

我在Ubuntu和jQuery 1.10.2下运行Chromium。

更多详情

调试器在调用堆栈上的函数下面显示以下内容。 我不假装理解它。

 (function() {with (this[2]) {with (this[1]) {with (this[0]) {return function(event) {undo_changes(this.parentNode) };}}}}) 

出于某种原因,在离开我的函数时,执行会跳转到第4761行的jQuery。之后,jQuery以某种方式调用我的函数box_click() ,它创建了我想要删除的内容。

按要求

当我输入此编辑时,问题已经解决。 然而,我被要求显示box_click() ,它创建了编辑界面。 这是我最初发布问题时的最新版本:

 function box_click() { if(cell_contents) { alert('Please deal with the other place you\'re editing first.'); return false; } var id = this.id; var student_id = $(this).attr('student_id'); var class_date = $(this).attr('date'); var html = make_radio('attendance','None',get_current(this) == 'None'); html += make_radio('attendance','Present',get_current(this) == 'Present'); html += make_radio('attendance','Absent',get_current(this) == 'Absent'); html += make_radio('attendance','Tardy',get_current(this) == 'Tardy'); html += ''; html += ''; html += ''; cell_contents = this.innerHTML; var f = $(main_form); main_form_destination = f.attr('action'); f.attr('action', '/classes/ajax_update_attendance/'+id+'/').attr('onchange', 'submit(this)'); // There's a smattering of PHP on this line this.innerHTML = html; $(this).unbind('click'); } 

bfavaretto的以下评论解决了我的问题:

我相信那是因为你的点击事件正在冒泡。 并且您无法通过内联处理程序阻止它,使用jquery绑定按钮单击。

我怀疑你遇到的情况是每次你的undo_changes函数运行时都会有额外的点击事件绑定到元素。 如果您尝试这样做怎么办:

  $(el).unbind('click').bind('click', box_click); 

这将确保只有当前单击处理程序将绑定到该元素的click事件。