如何为Collapsible-List的所有header/body统一添加文本或按钮?
实现方案
你可以直接使用以下jQuery或者原生JavaScript代码实现需求,代码逻辑简单易懂,适合新手学习:
前置要求
如果使用jQuery版本的代码,请确保你已经在页面中提前引入了jQuery库。
jQuery实现代码
$(function() { // 第一个按钮点击事件:为id=1的折叠列表所有头部追加指定文本 $('#collapsible-header-green').click(function() { $('#1 .collapsible-header').append(' Hello my name is Max'); }); // 第二个按钮点击事件:为id=2的折叠列表所有内容区域新增自定义按钮 $('#collapsible-body-green').click(function() { // 可自定义按钮的样式、文本、点击事件 const customButton = `<button class="btn green">我的自定义按钮</button>`; $('#2 .collapsible-body').append(customButton); }); });
代码说明
append()方法会在选中元素的现有内容末尾追加新内容,不会覆盖原有内容,如果你需要替换原有头部文本,可以将append替换为text('你要替换的全部文本')- 自定义按钮的class、文本可以根据你的需求随意修改,要给按钮加点击事件的话,直接在按钮标签里加
onclick="你的方法名()"即可。
原生JavaScript实现代码(不需要引入jQuery)
document.addEventListener('DOMContentLoaded', function() { // 第一个按钮点击逻辑 document.querySelector('#collapsible-header-green').addEventListener('click', function() { const headerList = document.querySelectorAll('#1 .collapsible-header'); headerList.forEach(header => { header.textContent += ' Hello my name is Max'; }); }); // 第二个按钮点击逻辑 document.querySelector('#collapsible-body-green').addEventListener('click', function() { const bodyList = document.querySelectorAll('#2 .collapsible-body'); bodyList.forEach(body => { const newBtn = document.createElement('button'); newBtn.className = 'btn green'; newBtn.textContent = '我的自定义按钮'; // 给自定义按钮加点击事件可以写:newBtn.onclick = () => { alert('按钮被点击了') } body.appendChild(newBtn); }); }); });
内容的提问来源于stack exchange,提问作者Idraf Jabas
相关产品推荐
相关产品推荐

