我在双击时可以编辑表格的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传播到其父级?
答案 0 :(得分:10)
或者某些人停止将所有事件从可编辑div传播到其父级?
这可能不是很可口,但
$(this).on("select mousedown mouseup dblclick etc", false);
(假设this
指的是您正在编辑的单元格。)
毕竟,事件数量有限,on
允许您在空格分隔的字符串中列出它们,并通过传递false
来禁用它们。
然后,您可以通过将相同的列表和false
再次传递到off
来重新启用它们。
答案 1 :(得分:4)
使用on / 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();
});