如果已经输入文本,JavaScript不会复制innerHTML

时间:2018-10-23 21:21:05

标签: javascript html innerhtml

当用户单击按钮以将div中一系列段落的文本复制到文本区域输入字段时,我正在运行以下代码。当文本区域为空时,代码可以正常工作,并将段落文本粘贴到字段中。如果再次按下该按钮,它也将重复该功能,将段落文本附加到先前粘贴的文本上。

但是,如果我在文本字段中手动输入任何内容,然后单击按钮,那么它将无法正常工作。

function copyDiv() {
  var x = document.getElementById('post-caption').getElementsByTagName('p');
  var i;
  var firstDivContent = x[0].innerHTML;
  for (i = 1; i < x.length; i++) {
    firstDivContent = firstDivContent + x[i].innerHTML;
  }
  var secondDivContent = document.getElementById('comment');
  firstDivContent = firstDivContent + " " + secondDivContent.innerHTML;
  secondDivContent.innerHTML = firstDivContent;
}

相应的HTML如下:

<div class="entry themeform" id="post-caption">
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
</div>
<input name="submit" type="submit" id="submit" class="submit" value="Send Feedback">
<textarea id="comment" name="comment" cols="45" rows="8" aria-required="true">&nbsp;</textarea></p>
<input name="copy-text" id="copy-text" class="submit copy-text" value="Copy caption text" onClick="copyDiv();">

非常感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

使用value而不是innerHTML来访问textarea

(您也可以使用document.querySelectorAll('#post-caption p');

const button = document.querySelector('button');
button.addEventListener('click', copyDiv, false);

function copyDiv() {
  var x = document.getElementById('post-caption').getElementsByTagName('p');
  var i;
  var firstDivContent = x[0].innerHTML;
  for (i = 1; i < x.length; i++) {
    firstDivContent = firstDivContent + x[i].innerHTML;
  }
  var secondDivContent = document.getElementById('comment');
  firstDivContent = firstDivContent + " " + secondDivContent.value;
  secondDivContent.value = firstDivContent;
}
<div id="post-caption">
  <p>Hallo</p>
  <p>Test</p>
  <p>This</p>
</div>
<textarea id="comment"></textarea>
<button>Click</button>

答案 1 :(得分:1)

在获取/设置内容方面,Textarea的行为与div不同。您需要$textarea.innerHTML而不是$textarea.value。查看此帖子JavaScript get TextArea input via .value or .innerHTML?

function copyDiv() {
  var x = document.getElementById('post-caption').getElementsByTagName('p');
  var i;
  var firstDivContent = x[0].innerHTML;
  for (i = 1; i < x.length; i++) {
    firstDivContent = firstDivContent + x[i].innerHTML;
  }
  var secondDivContent = document.getElementById('comment');
  var newContent = firstDivContent + " " + secondDivContent.value;
  secondDivContent.value = newContent;
}
<button onClick="copyDiv()">Copy</button>

<div id="post-caption">
  <p>this is the first</p>
  <p>this is the second</p>
  <p>this is the third</p>
</div>

<textarea id="comment">This is a comment</textarea>