我希望我能解释我遇到的这个“问题”。
它正在工作...但是我相信我可以用更少的代码来完成它。 让我告诉你我到目前为止所拥有的。我不在乎是否需要更改可编辑的div。
/* I don't like messy code */
var header = document.getElementById('header');
var lead = document.getElementById('lead');
var article = document.getElementById('article');
header.addEventListener("blur", render);
header.addEventListener("focus", edit);
lead.addEventListener("blur", render);
lead.addEventListener("focus", edit);
article.addEventListener("blur", render);
article.addEventListener("focus", edit);
function render() {
this.setAttribute("XPQ", this.innerHTML );
this.innerHTML = 'dynamic data from db (example) bla, bla bla bla and more bla';
}
function edit() {
this.innerHTML = this.getAttribute("XPQ");
}
/*
--- CSS Isn't important ---
*/
body{font-family:arial}h4{colour:red;}strong{colour:blue;}h4#header,#lead,#article{background:rgba(205,205,5,0.1);padding:3px;}
<h4 id="header" contenteditable="true" xpq="$post[1]['header'] -- (example)">dynamic data from db (example)</h4>
<p><strong id="lead" contenteditable="true" xpq="$example">this is the same as above (example)</strong></p>
<p id="article" contenteditable="true" xpq="/html/body/div[1]"> but of course all 3 have difrent data. I just tried to keep is simple to explain my problem. My idea is to use Javascript with PHP. Only I'm not so great with Javascript jet. I wonder if there was a clear way to make the JS. Without using on every element a blur and focus listener.</p>
我很好奇如何改善代码。 感谢您的帮助。
答案 0 :(得分:1)
通过单独使用getElementById
将事件侦听器添加到所有元素是不好的。您可以在所有想要具有此行为的元素上使用相同的类。然后使用querySelectorAll
来获取它们,并使用forEach
到addEventListner
上
document.querySelectorAll('.editable').forEach(x => {
x.addEventListener("blur", render);
x.addEventListener("focus", edit);
})
function render() {
this.setAttribute("XPQ", this.innerHTML );
this.innerHTML = 'dynamic data from db (example) bla, bla bla bla and more bla';
}
function edit() {
this.innerHTML = this.getAttribute("XPQ");
}
/*
--- CSS Isn't important ---
*/
body{font-family:arial}h4{colour:red;}strong{colour:blue;}h4#header,#lead,#article{background:rgba(205,205,5,0.1);padding:3px;}
<h4 id="header" class="editable" contenteditable="true" xpq="$post[1]['header'] -- (example)">dynamic data from db (example)</h4>
<p><strong id="lead" class="editable" contenteditable="true" xpq="$example">this is the same as above (example)</strong></p>
<p id="article" class="editable" contenteditable="true" xpq="/html/body/div[1]"> but of course all 3 have difrent data. I just tried to keep is simple to explain my problem. My idea is to use Javascript with PHP. Only I'm not so great with Javascript jet. I wonder if there was a clear way to make the JS. Without using on every element a blur and focus listener.</p>