javascript - 如何使用 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>
解决方案
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 不受欢迎的原因的更多信息。
推荐阅读
- javascript - 一个功能中的两个捕获
- python - 缺少爬网程序结果
- wso2 - WSO2 APIM 标头架构验证
- c++ - pragma push/pop_macro 指令堆栈是否对每个宏都是唯一的?
- android - 使用 appbarlayout 在 Scrollview 中固定 tablayout
- c# - 锁定屏幕 xamarin 形成时播放媒体元素
- android - Android Substratum 更改亮度和音量条
- reactjs - 使用 React Hooks 在页面加载时滚动到元素
- excel - 如何用逗号分隔,后跟 8(n)位数值?(Excel VBA)
- mysql - MySQL没有通过python连接