[英]DOM manipulation in vanilla JS
當多個具有相同類的元素時,如何訪問clicked事件的父元素? 我正在嘗試修改最接近的兄弟姐妹的內容。
該示例包含其應做的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選擇器一起使用,找到帶有class="note"
的td
元素。
我還使用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.