memo
// 取得所有的tr元素
var rows = document.querySelectorAll("table tr");
// 創建三個按鈕的模板
function createButton(iconClass, buttonText, clickHandler) {
var button = document.createElement("button");
var icon = document.createElement("i");
icon.className = iconClass;
button.appendChild(icon);
button.appendChild(document.createTextNode(buttonText));
button.onclick = clickHandler;
return button;
}
// 為每個tr元素創建下拉選單和按鈕
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
// 創建下拉選單元素
var dropdown = document.createElement("select");
dropdown.className = "dropdown";
// 創建第一個選項
var firstOption = document.createElement("option");
var icon = document.createElement("i");
icon.className = "fas fa-ellipsis-v";
firstOption.appendChild(icon);
dropdown.add(firstOption);
// 創建編輯按鈕
var editButton = createButton("fas fa-edit", "編輯", function() {
var target = this.getAttribute("data-target");
window.location.href = target;
});
// 創建複製按鈕
var cloneButton = createButton("fas fa-copy", "複製", function() {
// 複製當前的tr元素
var clonedRow = row.cloneNode(true);
row.parentNode.insertBefore(clonedRow, row.nextSibling);
});
// 創建刪除按鈕
var deleteButton = createButton("fas fa-trash-alt", "刪除", function() {
// 刪除當前的tr元素
row.parentNode.removeChild(row);
});
// 將下拉選單和按鈕添加到tr元素的第一個單元格中
var firstCell = row.cells[0];
firstCell.insertBefore(dropdown, firstCell.firstChild);
firstCell.appendChild(editButton);
firstCell.appendChild(cloneButton);
firstCell.appendChild(deleteButton);
// 設定編輯按鈕的data-target屬性為指定的URL
var target = "http://example.com/edit/" + i;
editButton.setAttribute("data-target", target);
// 當選擇一個選項時,執行相應的操作
dropdown.onchange = function() {
var selectedOption = this.options[this.selectedIndex];
var selectedValue = selectedOption.value;
if (selectedValue == "edit") {
editButton.click();
} else if (selectedValue == "clone") {
cloneButton.click();
} else if (selectedValue == "delete") {
deleteButton.click();
}
};
}
この記事が気に入ったらサポートをしてみませんか?