Настройте таргетинг на каждый div (то же имя класса) и скопируйте его содержимое в другой div в Javascript - PullRequest
0 голосов
/ 01 августа 2020

У меня есть несколько div с одинаковым именем класса. Как настроить таргетинг на каждый div и скопировать его содержимое в другой div, отредактировать содержимое и скопировать его обратно в исходный div? Вот мой код; HTML

<div id="div-editor">
    <h1>Title of div to be edited goes here</h1>
    <p>Paragraph of div to be edited goes here</p>
</div>
<div class="div-content" onclick="makeDivEditable()">
    <h1>Div one title</h1>
    <p>Copy the content of div ONE and make it editable in the div editor</p>
</div>

<div class="div-content" onclick="makeDivEditable()">
    <h1>Div two title</h1>
    <p>Copy the content of div TWO and make it editable in the div editor</p>
</div>

<div class="div-content" onclick="makeDivEditable()">
    <h1>Div three</h1>
    <p>Copy the content of div THREE and make it editable in the div editor</p>
</div>

<div class="div-content" onclick="makeDivEditable()">
    <h1>Div four title</h1>
    <p>Copy the content of div FOUR and make it editable in the div editor</p>
</div>

JavaScript

function makeDivEditable(){
  var divContent = document.getElementsByClassName('div-content');
  var divEditor = document.getElementById('div-editor');
  divEditor.innerHTML = divContent[0].innerHTML;
  divEditor.contentEditable = true;
}

Этот код влияет только на первый div (div one), как мне сделать так, чтобы он повлиял и на другие div? Я хочу, чтобы при нажатии на любой из div его содержимое копировалось в div-editor. Как только я закончу редактирование sh, он должен быть скопирован обратно в исходный div.

Ответы [ 3 ]

1 голос
/ 01 августа 2020

Я бы сделал ниже:

let currentEditingNode;
const defaultEditingNodeContent = document.getElementById('div-editor').innerHTML;

window.makeDivEditable = function makeDivEditable(e = window.event){
  var divContent = (e.target || e.srcElement).parentElement;
  var divEditor = document.getElementById('div-editor');
  divEditor.innerHTML = divContent.innerHTML;
  divEditor.contentEditable = true;
  currentEditingNode = divContent;
}

window.submitEdit = function submitEdit() {
  if (currentEditingNode) {
       var divEditor = document.getElementById('div-editor');
       currentEditingNode.innerHTML = divEditor.innerHTML;
       divEditor.contentEditable = false;
       divEditor.innerHTML = defaultEditingNodeContent;
  }
}
<div id="div-editor">
    <h1>Title of div to be edited goes here</h1>
    <p>Paragraph of div to be edited goes here</p>
</div>
<button id="submit-edit" onclick="submitEdit()">submit edit</button>
<div class="div-content" onclick="makeDivEditable(event)">
    <h1>Div one title</h1>
    <p>Copy the content of div ONE and make it editable in the div editor</p>
</div>

<div class="div-content" onclick="makeDivEditable(event)">
    <h1>Div two title</h1>
    <p>Copy the content of div TWO and make it editable in the div editor</p>
</div>

<div class="div-content" onclick="makeDivEditable(event)">
    <h1>Div three</h1>
    <p>Copy the content of div THREE and make it editable in the div editor</p>
</div>

<div class="div-content" onclick="makeDivEditable(event)">
    <h1>Div four title</h1>
    <p>Copy the content of div FOUR and make it editable in the div editor</p>
</div>

Вы можете поиграть с ним!

Обратите внимание, что я передаю event встроенным обработчикам событий, которые содержат выбранный целевой элемент . Поскольку вы хотите отредактировать весь родительский div, мне нужно было выбрать предка элемента, по которому щелкнули мышью. Обратите внимание: возможно, что элемент, возвращенный в event, может быть чем-то другим. Чтобы быть идеальным, я бы проверил, соответствует ли имя класса div-content (e.target || e.srcElement).parentElement перед копированием содержимого

0 голосов
/ 01 августа 2020

использовать текстовое поле, а не div

var divs;
var cnt;
var divEditor;
function makeDivEditable(){

divs = document.getElementsByClassName('div-content');

for(let i=0;i<divs.length;i++){   
   if(event.target == divs[i].getElementsByTagName('h1')[0]  ){
    cnt = i;  
    console.log(event.target.innerHTML);
    divEditor = document.getElementById('div-editor');
    divEditor.value = event.target.innerHTML;
    console.log(cnt);
        }}
  
}

function myUpdate(){
   var text = document.getElementById('div-editor').value;
   divs[cnt].getElementsByTagName('h1')[0].innerHTML = text;
   cnt=0;
}
textarea{
width:100%;}
<textarea id="div-editor" onchange="myUpdate()">
    <h1>Title of div to be edited goes here</h1>    
</textarea>

<textarea id="div-editor2" onchange="myUpdate()">
    <p>Paragraph of div to be edited goes here</p>  
</textarea>


<div class="div-content" onclick="makeDivEditable()">
    <h1>Div one title</h1>
    <p>Copy the content of div ONE and make it editable in the div editor</p>
</div>

<div class="div-content" onclick="makeDivEditable()">
    <h1>Div two title</h1>
    <p>Copy the content of div TWO and make it editable in the div editor</p>
</div>

<div class="div-content" onclick="makeDivEditable()">
    <h1>Div three</h1>
    <p>Copy the content of div THREE and make it editable in the div editor</p>
</div>

<div class="div-content" onclick="makeDivEditable()">
    <h1>Div four title</h1>
    <p>Copy the content of div FOUR and make it editable in the div editor</p>
</div>
0 голосов
/ 01 августа 2020

Почему бы не использовать обработчик событий onclick вместо добавления его в качестве атрибута в DOM? Затем используйте объект события, предоставленный обработчику события.

<div id="div-editor">
  <h1>Title of div to be edited goes here</h1>
  <p>Paragraph of div to be edited goes here</p>
</div>
<div class="div-content">
  <h1>Div one title</h1>
  <p>Copy the content of div ONE and make it editable in the div editor</p>
</div>

<div class="div-content">
  <h1>Div two title</h1>
  <p>Copy the content of div TWO and make it editable in the div editor</p>
</div>

<div class="div-content">
  <h1>Div three</h1>
  <p>Copy the content of div THREE and make it editable in the div editor</p>
</div>

<div class="div-content">
  <h1>Div four title</h1>
  <p>Copy the content of div FOUR and make it editable in the div editor</p>
</div>
let content_divs = new Array(...document.getElementsByClassName("div-content"));
content_divs.forEach((div) => {
  div.onclick = makeDivEditable;
});
function makeDivEditable(e) {
  let divEditor = document.getElementById("div-editor");
  divEditor.innerHTML=e.target.innerHTML;
}

Подробнее: https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...