javascript - vanilla JS 中的 DOM 操作
问题描述
当有多个相同类的元素时,如何访问单击事件的父元素?我正在尝试修改最接近的兄弟姐妹的内容。
该示例包含一个 jQuery 版本的它应该做什么。
我使用 'document' 作为 eventlisterner,因为 '.interactive-btn' 是动态添加的元素。
https://jsfiddle.net/gb8tr0nu/2/
HTML:
<table class="my-table">
<thead>
<tr>
<th>Account</th>
<th>Note</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<tr>
<td class="account">account one</td>
<td class="note">1234567890</td>
<td class="time">7/10/2018
<button class="interactive-btn">Button</button>
</td>
</tr>
<tr>
<td class="account">account two</td>
<td class="note">abcdefghijklmn</td>
<td class="time">7/10/2018
<button class="interactive-btn">Button</button>
</td>
</tr>
</tbody>
</table>
JS:
/* Vanilla */
document.addEventListener('click', (event) => {
if(event.target.className === 'interactive-btn') {
// get the closest .note content and chagne it.
}
});
/* Jquery */
$(document).on('click', '.interactive-btn', function(event) {
$(this).parent().siblings('.note').text('new text');
});
解决方案
如果您可以使用实验性功能,您可以使用Element.closest
查找祖先tr
,然后使用document.querySelector
CSS 选择器查找td
带有class="note"
.
我还使用了一个更丑陋(但仍然有效)的解决方案Node.parentElement
- 如果您重组 HTML,这将打破!
document.addEventListener('click', (event) => {
/*if (event.target.className === 'interactive-btn') {
//looks nice, but experimental - probably shouldn't be used in production code
var noteEl = event.target.closest('tr').querySelector('td[class=note]');
noteEl.innerHTML = 'Changed!'
}
});*/
if (event.target.className === 'interactive-btn') {
//a little uglier but works if your HTML structure doesnt change
var noteEl = event.target.parentElement.parentElement.querySelector('td[class=note]');
noteEl.innerHTML = 'Changed!'
}
});
<table class="my-table">
<thead>
<tr>
<th>Account</th>
<th>Note</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<tr>
<td class="account">account one</td>
<td class="note">1234567890</td>
<td class="time">7/10/2018
<button class="interactive-btn">Button</button>
</td>
</tr>
<tr>
<td class="account">account two</td>
<td class="note">abcdefghijklmn</td>
<td class="time">7/10/2018
<button class="interactive-btn">Button</button>
</td>
</tr>
</tbody>
</table>
推荐阅读
- git - 如何合并仅从遥远的过去提交中复制(未分支)的代码?
- ruby - 对生产环境中未经允许的参数的操作
- c# - SSIS 错误“分配 104851104 字节时缓冲区失败。”
- c# - 如何解析没有类、id 等的 html 元素
- vba - 使用每行上的复选框选择表单行
- php - 反应本机图像上传不适用于 PHP 远程服务器 URL
- wordpress - 为什么我不能显示来自 ACF 字段的图像?
- typo3 - 仅对 pages 表禁用 sys_file_reference_field
- asp.net - 无法在 XmlDocument 中加载字符串
- excel - 如何查找日期时间单元格是“AM”还是“PM”并在不同的列中返回值?