我正在尝试编辑表格中的数据并选择在 <td>
内的 div 上使用 contentEditable s,我遇到了一个非常奇怪的问题。当我第一次去编辑它时,我必须点击两次,之后每隔一次我只需要点击一次。但在第一次尝试编辑时,我必须点击两次。这是我的 HTML 中的示例表格行:
<tr style="width:100%"> <td><div class="results" onblur="blurMe(event)" onclick="darkenBox(event)" onkeypress="enterKey(event)" >Adam McGurk</div></td><td><div class="results" onblur="blurMe(event)" onkeypress="enterKey(event)" onclick="darkenBox(event)">amcgurk@shinesolar.com</div></td><td class="delete-sales-person"><span class="delete-icon"></span></td></tr>
这是合适的 JS:
//Only to be used with changing data to gray on click and border on hover.
function darkenBox(e){
const ele = e.path[0];
ele.setAttribute("contenteditable", true);
console.log("Editing cell data");
ele.classList.add("darkenBox")
}
// Allows user to edit content by click
function clickEdit(e) {
e.path[0].setAttribute("contenteditable", true);
}
//Deleted placeholder text on click
function clearText(e) {
const ele = e.path[0];
ele.setAttribute("contenteditable", true);
ele.innerText='';
}
// Allows user to stop editing by pressing the, "Enter" key.
function enterKey(e){
const keyCode = e.keyCode;
const ele = e.path[0];
if (keyCode === 13) {
ele.classList.remove("darkenBox");
ele.setAttribute("contenteditable", false);
}
}
function blurMe(e) {
const editedElement = e.path[0];
editedElement.classList.remove("darkenBox");
}
为什么第一次编辑需要点击两次?
最佳答案
第一次单击它时,它会将 contenteditable
设置为 true
。单击并不会取消设置。第二次单击时,contenteditable
仍然是 true
。这使您可以激活元素并立即对其进行编辑。如果你想在第一次点击时编辑它,你可以让你想要编辑的所有元素都以 contenteditable
启用。或者,您可以在启用 contenteditable
后聚焦该元素。
ele.setAttribute("contenteditable", true);
ele.focus();
顺便说一下,这目前在 firefox 上根本不起作用,我建议您使用 e.target
而不是 e.path[0]
。
关于javascript - 在 contentEditable 上使用元素,第一次编辑需要点击两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55288791/