要将按钮容器插入到一个特定的表格(<table>
)中,比如在 keyInfo
表格中的第二个 <tr>
之后,您可以使用类似以下的 JavaScript 代码来实现:
// 找到包含合同信息的表格,例如通过其 class 或 id 选择器
const keyInfoTable = document.querySelector('table.keyInfo'); // 请根据实际情况修改选择器
if (keyInfoTable) {
// 找到第二个<tr>
const secondRow = keyInfoTable.querySelectorAll('tr')[1]; // 获取所有<tr>,索引1是第二行
if (secondRow) {
// 创建按钮容器
const buttonContainer = document.createElement('div');
buttonContainer.innerHTML = `
<div class="button-container">
<button class="btn" data-action="action1">按钮1</button>
<button class="btn" data-action="action2">按钮2</button>
<button class="btn" data-action="action3">按钮3</button>
<button class="btn" data-action="action4">按钮4</button>
</div>
`;
// 将按钮容器插入到第二个<tr>之后
secondRow.parentNode.insertBefore(buttonContainer, secondRow.nextSibling);
// 添加点击事件处理函数
buttonContainer.querySelectorAll('.btn').forEach(button => {
button.addEventListener('click', function() {
const action = this.getAttribute('data-action');
switch (action) {
case 'action1':
console.log('按钮1被点击');
break;
case 'action2':
console.log('按钮2被点击');
break;
case 'action3':
console.log('按钮3被点击');
break;
case 'action4':
console.log('按钮4被点击');
break;
default:
break;
}
});
});
}
}
说明:
选择表格:使用合适的选择器找到
keyInfo
表格。定位第二行:通过
querySelectorAll('tr')
方法获取所有的<tr>
,并使用索引[1]
来获取第二个<tr>
。创建并插入按钮容器:创建一个新的 div 元素来放置您的按钮,并使用
insertBefore()
方法将这个 div 插入到第二个<tr>
后面。
注意事项:
- 请确保
keyInfo
表格和它的内容在 DOM 中存在,以免导致错误。 - 根据项目实际 HTML 结构和 CSS 类名调整选择器。
内容由零声教学AI助手提供,问题来源于学员提问