首页 > 解决方案 > 如何使用 html 和 javascipt 或 jquery 在按钮单击时编辑 div 内容?

问题描述

我正在尝试使用 javascript 在编辑单击时编辑 div 内容,但在按钮单击时,我的段落标签既不编辑也不聚焦。

我已经从 w3schools 尝试过这段代码,但这段代码对我不起作用。

function myFunction() {
  document.getElementById("myP").contenteditable = true;
  document.getElementById("demo").innerHTML = "The p element above is now editable. Try to change its text.";
}
<p id="myP">This is a paragraph. Click the button to make me editable.</p>
<button onclick="myFunction()">Try it</button>

标签: javascriptjqueryhtmlcss

解决方案


JavaScript 区分大小写,正确的属性 iscontentEditable和 notcontenteditable

function myFunction() {
  document.getElementById("myP").contentEditable = true;
  document.getElementById("demo").innerHTML = "The p element above is now editable. Try to change its text.";
}
<p id="myP">This is a paragraph. Click the button to make me editable.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

如果您不确定对象的属性名称,您可以遍历其所有属性。或者使用 google/mdn 查看相关页面。即MDN HTMLElement

for (var key in HTMLParagraphElement.prototype) {
  if (/content|edit/i.test(key)) console.log(key);
}

HTML 元素的大多数属性都可以使用属性和属性来访问/更改。在您的情况下,您可以使用setAttribute("contenteditable", "true").

function myFunction() {
  document.getElementById("myP").setAttribute("contenteditable", "true");
  document.getElementById("demo").innerHTML = "The p element above is now editable. Try to change its text.";
}
<p id="myP">This is a paragraph. Click the button to make me editable.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

这是一种动态添加事件侦听器的方法:

document.getElementById("editMyP").addEventListener("click", function(event) {
  document.getElementById("myP").contentEditable = true;
  document.getElementById("demo").innerHTML = "The p element above is now editable. Try to change its text.";
  event.preventDefault();
});
<p id="myP">This is a paragraph. Click the button to make me editable.</p>
<button id="editMyP">Try it</button>
<p id="demo"></p>

边注:

您说您使用的是 w3schools,虽然它们最近有所改进,但我建议您使用不同的平台。您可以在此处阅读有关 w3schools 不受欢迎的原因的更多信息。


推荐阅读