暂时禁用所有当前活动的jQuery事件处理程序
我在双击时可以编辑表格的TD
元素:
$(document).on("dblclick", "#table>tbody>tr>td.cell", function(e) { if (e.which != 1 || e.shiftKey || e.altKey || e.ctrlKey) // need left button without keyboard modifiers return; reset_selection(); var editor = document.createElement("div"); editor.setAttribute("contenteditable", "true"); editor.innerHTML = this.innerHTML; this.innerHTML = ''; // this.style.padding = 0; this.appendChild(editor); $(document).on("*", stub); editor.onblur = function() { // this.parentNode.setAttribute("style", ""); this.parentNode.innerHTML = this.innerHTML; sys.editor = null; $(document).off("*", stub);; }; editor.focus(); }); function stub(e) { e.stopImmediatePropagation(); return false; }
但是,当我双击可编辑div内的文本时,双击事件会传播到父td,从而导致意外后果。 还有其他我想要阻止的事件( select
, mousedown
等),所以为每个事件编写一个存根对我来说并不好看。
有没有办法禁用所有当前活动的jQuery事件处理程序并在之后启用它们? 或者有些人会停止将所有事件从可编辑div传播到其父级?
或者有些人会停止将所有事件从可编辑div传播到其父级?
它可能不是很可口,但具体禁用事件并不是那么糟糕:
$(this).on("select mousedown mouseup dblclick etc", false);
(假设this
是指您正在编辑的单元格。)
毕竟,事件数量有限,而且允许您在空格分隔的字符串中列出它们,并通过传递false
禁用它们。
然后,您可以通过传递相同的列表重新启用它们,并再次将其设置为off
。
使用开/关JQuery方法:
var myFunction = function(e) { if (e.which != 1 || e.shiftKey || e.altKey || e.ctrlKey) // need left button without keyboard modifiers return; reset_selection(); var editor = document.createElement("div"); editor.setAttribute("contenteditable", "true"); editor.innerHTML = this.innerHTML; this.innerHTML = ''; // this.style.padding = 0; this.appendChild(editor); $(document).on("*", stub); editor.onblur = function() { // this.parentNode.setAttribute("style", ""); this.parentNode.innerHTML = this.innerHTML; sys.editor = null; $(document).off("*", stub);; }; editor.focus(); }; function stub(e) { e.stopImmediatePropagation(); return false; } //Active the events $(document).on("dblclick", "#table>tbody>tr>td.cell", myFunction); //Disable the events $(document).off("dblclick", "#table>tbody>tr>td.cell",myFunction); //Reactive the events $(document).on("dblclick", "#table>tbody>tr>td.cell", myFunction);
更新
如果不考虑事件,您还可以将变量设置为true
:
var skipEvent = true; $(document).on("dblclick", "#table>tbody>tr>td.cell", function (e) { //Check variable and skip if true if (skipEvent) return false; if (e.which != 1 || e.shiftKey || e.altKey || e.ctrlKey) // need left button without keyboard modifiers return; reset_selection(); var editor = document.createElement("div"); editor.setAttribute("contenteditable", "true"); editor.innerHTML = this.innerHTML; this.innerHTML = ''; // this.style.padding = 0; this.appendChild(editor); $(document).on("*", stub); editor.onblur = function () { // this.parentNode.setAttribute("style", ""); this.parentNode.innerHTML = this.innerHTML; sys.editor = null; $(document).off("*", stub);; }; editor.focus(); });