JS专注于更改查询,显示模糊

时间:2019-04-13 02:39:22

标签: javascript addeventlistener innerhtml

我希望我能解释我遇到的这个“问题”。

  • 我要单击文本(在我的情况下为可编辑div)
  • 编辑“代码/命令/查询/指令
  • 发布/模糊后,将内部内容替换为生成的数据

它正在工作...但是我相信我可以用更少的代码来完成它。 让我告诉你我到目前为止所拥有的。我不在乎是否需要更改可编辑的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>

我很好奇如何改善代码。 感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

通过单独使用getElementById将事件侦听器添加到所有元素是不好的。您可以在所有想要具有此行为的元素上使用相同的类。然后使用querySelectorAll来获取它们,并使用forEachaddEventListner

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>