javascript - 调用前一个兄弟作为函数参数?
问题描述
我正在构建一个小写信工具,其中包含用户可以选择添加到信中的一系列段落,但我担心我这样做的效率非常低。
目前,它的结构如下:
<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
解决方案
每个都box
包含一个段落和一个按钮。
我们可以得到所有的boxes
和每个box
段落和按钮,最后添加click event
到button
插入的paragraph html
这个box
到textarea
// 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>
推荐阅读
- reactjs - 使用 react-data-export 导出时,使用 mirosoft excel 在 .xlsx 文件中看不到填充和字体颜色
- python - 列必须与关键错误熊猫数据框问题的长度相同
- r - 如何将矩阵提取到子矩阵
- c# - 如何使用 C# 将文件夹从一个目录移动到另一个目录?
- bash - 如何使用 bash 从文件中获取特定文本
- python - 如何从字符串中提取某些元素?
- java - API 服务返回计算价格并在完成时将其显示在前端
- html - CSS - 登陆页面图像上的波浪边框,不仅仅是波浪
- diagram - 绘制数学图首选 MathJax 的哪个库?
- java - 检查 Internet 是否可用 - 我们是否也应该检查 NetworkCapabilities.TRANSPORT_BLUETOOTH、TRANSPORT_VPN 等?