javascript 如何使用循环将innerText从一组元素复制到另一组元素?

rseugnpd  于 2023-11-15  发布在  Java
关注(0)|答案(2)|浏览(171)

如何使用for循环让document.getElementById通过单击提交按钮复制多个?
在ID部分:

  • a1拷贝到b1
  • a2复制到b2
  • a3拷贝到b3
  • a4复制到b4
function transferData() {
  // Get the content of the first blockquote
  var content1 = document.getElementById('a1').innerText;

  // Set the content of the second blockquote
  document.getElementById('b1').innerText = content1;
}

个字符

y1aodyip

y1aodyip1#

假设我已经正确理解了你的目标,那么实现这个目标的最简单的方法就是将每一组blockquote元素 Package 在一个容器中。然后你可以通过索引直接将它们相互关联。这将消除对它们的任何其他标识符的需要。
优点:轻量级的HTML,不需要JS实现的知识。简单的逻辑。
缺点:需要与目标相同数量的源元素,因此可能会因对HTML的不小心更新而被破坏。

const sources = document.querySelectorAll('.source > blockquote');
const targets = document.querySelectorAll('.target > blockquote');

document.querySelector('#copy').addEventListener('click', () => {
  sources.forEach((el, i) => targets[i].innerText = el.innerText);
});

个字符
无论出于何种原因,如果您不希望通过索引将它们关联起来,那么您可以使用data属性来通过其id设置目标:

const sources = document.querySelectorAll('.source > blockquote');

document.querySelector('#copy').addEventListener('click', () => {
  sources.forEach((el, i) => document.querySelector(el.dataset.target).innerText = el.innerText);
});
<div class="source">
  first
  <blockquote contenteditable="true" id="s1" data-target="#t1"><p>text1</p></blockquote>
  <blockquote contenteditable="true" id="s2" data-target="#t2"><p>text2</p></blockquote>
  <blockquote contenteditable="true" id="s3" data-target="#t3"><p>text3</p></blockquote>
  <blockquote contenteditable="true" id="s4" data-target="#t4"><p>text4</p></blockquote>
</div>
<div class="target">
  second
  <blockquote contenteditable="true" id="t1"><p></p></blockquote>
  <blockquote contenteditable="true" id="t2"><p></p></blockquote>
  <blockquote contenteditable="true" id="t3"><p></p></blockquote>
  <blockquote contenteditable="true" id="t4"><p></p></blockquote>
</div>

<button type="button" id="copy">Submit</button>

的字符串
优点:如果需要更改目标元素选择器,则具有健壮性和可扩展性
缺点:需要额外的HTML来定位正确的元素。
两者都可以工作,这取决于你的确切用例,哪一个适合你。

4si2a6ki

4si2a6ki2#

在这里,我们得到了所有以a开头的ID元素,比如a1
然后,我们循环所有这些,并将其innerText添加到b + indexidblockquote,其中index是循环操作的索引。(我们加1,因为数组索引从0开始)。
这有缺点,它假设一切都是有序的,它假设有等量的a和B,它还假设这些元素是页面上唯一的元素,但这应该是一个很好的起点。

function transferData() {
  const els = document.querySelectorAll("blockquote[id^=a]")
  els.forEach((el, idx) => {
    document.getElementById(`b${idx + 1}`).innerText = el.innerText
  });
 }

个字符

相关问题