我正在尝试编辑表中保存的数据,并选择在<td>
内的div上使用contentEditable,但我遇到了一个非常奇怪的问题。第一次进行编辑时,我必须单击两次,然后每隔两次单击一次。但是在第一次尝试编辑时,我必须单击两次。这是我的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");
}
为什么需要我单击两次才能进行第一次编辑?
最佳答案
您的div开始时没有contenteditable设置。第一次单击它们时,您将contenteditable设置为true,但是单击已被处理,因此不会触发编辑。
只有在下一次单击时,浏览器才允许编辑,因为现在contenteditable为true。
直接在html中将contenteditable设置为true即可使用。
关于javascript - 在contentEditable上使用元素需要两次单击才能进行第一次编辑,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55288791/