[英]JS inserting content multiple times
我正在研究一個僅顯示指定行數並具有切換按鈕以顯示所有行的函數。 我遇到的問題是,如果頁面上有多個表,則切換按鈕將顯示多次。 如果有兩個表,則每個表后將顯示兩個按鈕。 如果有三個,則每個表格后將顯示三個按鈕。
我想我知道執行此操作的代碼行,但是對於我自己的一生,我無法弄清楚。 我嘗試了insertAfter.forEach(table, toggleBar);
但這沒用。
attached() {
// Insert element after another
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
// Set multiple attributes on an element
function setAttributes(el, attrs) {
for (let key in attrs) {
el.setAttribute(key, attrs[key]);
}
}
// Toggle the rows on this table
function toggleRows(table, rows, count) {
// Loop through all the rows and toggle the hidden attribute
for (let i = count; i < rows.length; i++) {
rows[i].hidden ? rows[i].hidden = false : rows[i].hidden = true;
}
}
// Gather all the tables to truncate based on the data-truncate attribute
let truncatedTables = document.querySelectorAll('[data-truncate="true"]');
// For each table to truncate
truncatedTables.forEach(function(table) {
let visibleRowCount = table.dataset.displayRows;
let rows = table.querySelectorAll('tbody tr');
let toggleBar = document.createElement('div');
let toggle = document.createElement('button');
let toggleText = '+ ' + (rows.length - visibleRowCount) + ' More';
// Truncate the table
for (let i = visibleRowCount; i < rows.length; i++) {
rows[i].hidden = true;
}
// Style the toggle-bar and set appropriate attributes
toggleBar.className = 'toggle-bar';
toggleBar.append(toggle);
setAttributes(toggle, {
'role' : 'button',
'aria-expanded': 'false',
'aria-controls': table.id,
'data-action' : 'rowToggle',
'data-text' : '+ More',
'data-alttext' : '- Less'
});
// Edit the toggle text & alt text attribute
toggle.innerText = toggleText;
toggle.dataset.text = toggleText;
// Add the toggleBar after this table
insertAfter(table, toggleBar);
// When clicking the toggle
toggle.addEventListener('click', function() {
// Toggle the button based on aria-expanded attribute
if ( this.getAttribute('aria-expanded') === 'false' ) {
this.innerText = this.dataset.alttext;
this.setAttribute('aria-expanded', 'true');
} else {
this.innerText = this.dataset.text;
this.setAttribute('aria-expanded', 'false');
}
// Toggle the table rows
toggleRows(table, rows, visibleRowCount);
});
});
}
我正在使用Aurelia,所以我的看法很簡單。 我只是傳遞一些可綁定的屬性。
<template>
<table data-truncate="${tableTruncate}" data-display-rows="${tableRows}" id="${tableId}">...
</table>
</template>
我認為最可能的罪魁禍首是您的attached
函數被多次調用。 我猜這是一個事件處理程序,正在偵聽要附加到文檔的表或類似的表,並且每個表都被調用一次,因此3個表將導致添加3個按鈕。
有幾種解決方法。 您可以更改attached
的調用頻率; 如果已經有一個切換按鈕,可以在表上設置一個標志並跳過它; 或者您可以檢查切換按鈕是否已存在並進行更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.