首页 > 解决方案 > 调用前一个兄弟作为函数参数?

问题描述

我正在构建一个小写信工具,其中包含用户可以选择添加到信中的一系列段落,但我担心我这样做的效率非常低。

目前,它的结构如下:

<p id="deposit-dispute" class="paragraph">This is a paragraph about deposits not being protected</p>
<button onclick="addPara(depositDispute)" class="add">Add paragraph</button>

然后在 Javascript 中,我创建了一个 const 来提取该 id 的内部 HTML:

const depositDispute = "\n" + document.getElementById("deposit-dispute").innerHTML + "\n";

然后 addPara() 函数将其添加到 textarea:

function addPara(text) {
document.getElementById("text-body").value += text;
}

但是有没有办法让函数只调用前面p元素中的任何内容,而不是必须给它们所有唯一的 ID 并为它们创建一个唯一的变量?

它在一个 codepen 中,所以你可以看到我正在尝试做的事情 - 要添加的段落在右侧的手风琴中:https ://codepen.io/gordonmaloney/pen/GRWyjOP

非常感谢 - 如果这是一个荒谬的业余问题,我深表歉意,我花了很长时间试图用谷歌搜索解决方案,但找不到任何东西!

G

标签: javascript

解决方案


每个都box包含一个段落和一个按钮
我们可以得到所有的boxes和每个box 段落按钮,最后添加click eventbutton插入的paragraph html这个boxtextarea

// Get textarea and boxes
var textarea = document.getElementById('textarea');
var boxes = document.querySelectorAll('.box');

// get the button and the paragraph of each box 
boxes.forEach(box => {
    var btn = box.querySelector('.button');
    var paragraph = box.querySelector('.paragraph');
    // add the html of the selected box paragraph to the textarea 
    btn.addEventListener('click', () => {
        textarea.value += "\n" + paragraph.innerHTML; + "\n";
    });
});
  <div class="wrapper">
      <div class="box">
          <p class="paragraph">This is paragraph 1</p>
          <button class="button">Add to textarea</button>
      </div>
      <div class="box">
          <p class="paragraph">This is paragraph 2</p>
          <button class="button">Add to textarea</button>
      </div>
      <div class="box">
          <p class="paragraph">This is paragraph 3</p>
          <button class="button">Add to textarea</button>
      </div>
 </div>
  
 <textarea name="" id="textarea" cols="30" rows="10"></textarea>


推荐阅读