在段落中创建按钮

时间:2020-12-21 15:05:11

标签: javascript html arrays button copy

我想在段落标签之后创建复制按钮。这是我正在使用的 html -

<div class="main"><p class="heading">Example Number One.</p></div>
<div class="main"><p class="heading">Example Number Two.</p></div>
<div class="main"><p class="heading">Example Number Three.</p></div>

我正在使用 Javascript 在每个 p 标签后添加按钮,但无法正常工作意味着所有按钮仅复制“示例第一”等。

我想这样做。

<div class="main"><p class="heading">Example Number One.</p><button class="copy-btn">Copy</button></div>
<div class="main"><p class="heading">Example Number Two.</p><button class="copy-btn">Copy</button></div>
<div class="main"><p class="heading">Example Number Three.</p><button class="copy-btn">Copy</button></div>

注意:=

  • 我想使用 & 使用纯 Javascript(无 Jquery)。

JAVASCRIPT

    const parentObject = document.getElementsByClassName('heading');
    [...parentObject].forEach((parent, i) => {
      const child = document.createElement('button');
      child.className = 'copy-btn';
     child.innerHTML = 'Copy';
      parent.appendChild(child)
    });

copyBtn = document.querySelector('.copy-btn');  
copyBtn.addEventListener('click', function(event) {  
  var para = document.querySelector('.heading');  
  var range = document.createRange();  
  range.selectNode(para);  
  window.getSelection().addRange(range);  
  
   var successful = document.execCommand('copy');  
  window.getSelection().removeAllRanges();  
});

2 个答案:

答案 0 :(得分:1)

这就是你想要的:

const parentObject = document.getElementsByClassName('heading');
[...parentObject].forEach((parent, i) => {
    const child = document.createElement('button');
    child.className = `copy-btn copy-btn-${i}`;
   child.innerHTML = 'Copy';
    parent.appendChild(child)
});

copyBtn = document.querySelectorAll('.copy-btn');
copyBtn.forEach(btn => {
    btn.addEventListener('click', () => {
        const parent = btn.parentElement;
        const range = document.createRange();
        range.setStart(parent, 0);
        range.setEnd(parent, 1);
        window.getSelection().addRange(range);
        var successful = document.execCommand('copy');
        window.getSelection().removeAllRanges();
    });
});
<div class="main"><p class="heading">Example Number One.</p></div>
<div class="main"><p class="heading">Example Number Two.</p></div>
<div class="main"><p class="heading">Example Number Three.</p></div>

答案 1 :(得分:0)

从上一个答案来看,标题不是父级。主要是

const parentObject = document.getElementsByClassName('main');