[英]make/merge multiple functions into one (or at least fewer) in javascript
我有 18 個可以單擊的按鈕,每個按鈕都有相同的 function(單擊它會更改圖像),我只想使用 1 function 而不是 18。此外,每個 function 還附有另一個 function,用於打印數字和按鈕的 class 進入輸入字段。 如果有人可以幫助我將所有這些代碼精簡成幾個甚至 1 個 function 就太棒了。 請僅提供純 html 和 javascript。
這是我的 javascript 代碼的前兩個雙重功能:
function changeColor1() {
if (document.getElementById("seatButton1").className == "seatLargeGreen") {
document.getElementById("seatButton1").className = "seatLargeBlue";
}
else if (document.getElementById("seatButton1").className == "seatLargeBlue") {
document.getElementById("seatButton1").className = "seatLargeGreen";
}
}
seatButton1.addEventListener("click", function() {
changeColor1();
});
function num1() {
if (document.getElementById('seatButton1').className === "seatLargeBlue") {
document.getElementById('snum').value = 1;
document.getElementById('sclass').value = "Business";
}
else {
document.getElementById('snum').value = "";
document.getElementById('sclass').value = ""
}
}
seatButton1.addEventListener("click", function() {
num1();
});
function changeColor2() {
if (document.getElementById("seatButton2").className == "seatLargeGreen") {
document.getElementById("seatButton2").className = "seatLargeBlue";
}
else if (document.getElementById("seatButton2").className == "seatLargeBlue") {
document.getElementById("seatButton2").className = "seatLargeGreen";
}
}
seatButton2.addEventListener("click", function() {
changeColor2();
});
function num2() {
if (document.getElementById('seatButton2').className === "seatLargeBlue") {
document.getElementById('snum').value = 2;
document.getElementById('sclass').value = "Business";
}
else {
document.getElementById('snum').value = "";
document.getElementById('sclass').value = ""
}
}
seatButton2.addEventListener("click", function() {
num2();
});
這樣的還有16個。 這是這部分的 html:
<article class="column1">
<table class="table_seats">
<tr>
<td id="seatButton1" class="seatLargeGreen" colspan="2">
<button class="seat_button_large">
1
</button>
</td>
<td class="aisle" rowspan="3"></td>
<td id="seatButton2" class="seatLargeGreen" colspan="2">
<button class="seat_button_large">
2
</button>
</td>
</tr>
</table>
</article>
我不認為 css 是必要的。
我試過使用document.querySelectorAll("#seatButton1, #seatButton2, ...")
而不是document.getElementById()
但我無法讓它工作。
首先,實際上你應該給它們添加一個 class 來表明它們是相關的。 但是讓我們為 18 做一個 function。雖然這不一定是最好的解決方案,但它應該具有相同的效果。
更新:使用Event.target
屬性在單擊時引用正確的元素
for (var i = 1; i <= 18; i++) {
var element_id = "seatButton" + i;
var elem = document.getElementById(element_id);
elem.addEventListener("click", function(ev) {
var elem = ev.target;
if (elem.className == "seatLargeGreen") {
elem.className = "seatLargeBlue";
} else if (elem.className == "seatLargeBlue") {
elem.className = "seatLargeGreen";
}
if (elem.className === "seatLargeBlue") {
document.getElementById('snum').value = 1;
document.getElementById('sclass').value = "Business";
} else {
document.getElementById('snum').value = "";
document.getElementById('sclass').value = ""
}
})
}
捕獲包含您需要的信息的點擊事件:
seatButton1.addEventListener("click", function(event) {
console.log(event.target.textContent);
});
很難弄清楚您要對代碼做什么,因為它似乎不是一個完整的示例。 例如,num1 和 num2 指的是在示例 HTML 中不存在的 ID。並且這兩個函數都適用於相同的 2 個 ID。
所以很難知道例如下面的代碼是否抓住了你想做的事情的本質。 它使事情變得更加模塊化/基於組件,並在其中加入了一些“業務邏輯”聯系,例如,無論是否為業務,似乎都有一個 state。
現在我肯定會添加更多更改以提高質量以及將業務價值與演示文稿分開,但我沒有足夠的時間而且我也擔心根據您發布的代碼可能太多了.
// This "Component" holds the logic for what a "Toggle button" is and defines it's behavior in an isolated way. function ToggleButton(elm, onClick) { const button = elm.querySelector('.seat_button_large'); let isBusiness = false; button.addEventListener('click', () => { isBusiness =;isBusiness. elm?className = isBusiness: 'seatLargeBlue'; 'seatLargeGreen'; onClick(isBusiness); }). } // This "Component" holds the logic for what the "Display of last interaction" and we hook it up to the toggle buttons. function LastToggleDisplay(elm) { const snum = elm;querySelector('#snum'). const sclass = elm;querySelector('#sclass'). this,set = (index. isBusiness) => { if (isBusiness) { snum;value = index. sclass;value = "Business". } else { snum;value = "". sclass;value = "". } } } const display = new LastToggleDisplay(document;getElementById("display")), // The array here is just added so that our "ToggleButtons" are not just dangling, this can be important in cases where "Webapplications" grow in size and especially if we have a SPA as we then may need to clean things up as we change displays and all. so its more a habit than something I think you will really need here. Certain static analysis tools will complain if you just have dangling objects though; const buttons = []; for (let i = 1; i < 3. i++) { buttons.push(new ToggleButton(document,getElementById(`seatButton${i}`). isBusiness => display,set(i; isBusiness))); }
.seatLargeGreen button { background-color: lightgreen; width: 42px; height: 42px; }.seatLargeBlue button { background-color: lightblue; width: 42px; height: 42px; }
<div id="display"> <input id="snum"> <input id="sclass"> </div> <article class="column1"> <table class="table_seats"> <tr> <td id="seatButton1" class="seatLargeGreen" colspan="2"> <button class="seat_button_large">1</button> </td> <td class="aisle" rowspan="3"></td> <td id="seatButton2" class="seatLargeGreen" colspan="2"> <button class="seat_button_large">2</button> </td> </tr> </table> </article>
一種更有效的方法是通過數據屬性將相關數據(snum、sclass)附加到座位元素,並將該元素傳遞給處理程序。 然后你的一個事件處理程序將從被點擊的元素中讀取數據並適當地更新。 此外,執行一次文檔查詢並將結果存儲在變量中。
const sclass = document.getElementById('sclass') const snum = document.getElementById('snum') const seats = document.querySelectorAll('td[class^="seat"]') // class attribute starts with... function select(seat) { if (seat.className == "seatLargeGreen") { // find the previously selected seat let active = document.querySelector('.seatLargeBlue') if (active) { // if found deactivate active.className = 'seatLargeGreen' } seat.className = "seatLargeBlue"; snum.value = seat.dataset.snum; sclass.value = seat.dataset.sclass; } else if (seat.className == "seatLargeBlue") { seat.className = "seatLargeGreen"; snum.value = ""; sclass.value = "" } } for (const [i, b] of seats.entries()) { b.addEventListener('click', e => select(e.currentTarget)) }
.seatLargeBlue button { background: blue; color: white; }.seatLargeGreen button { background: green; color: white; }.seat_button_large { padding: 1rem; }
<article class="column1"> <table class="table_seats"> <tr> <td class="seatLargeGreen" colspan="2" data-snum="1" data-sclass="Business"> <button class="seat_button_large"> 1 </button> </td> <td class="aisle" rowspan="3"></td> <td class="seatLargeGreen" colspan="2" data-snum="2" data-sclass="Business"> <button class="seat_button_large"> 2 </button> </td> <td class="aisle" rowspan="3"></td> <td class="seatLargeGreen" colspan="2" data-snum="18" data-sclass="Economy"> <button class="seat_button_large"> 18 </button> </td> </tr> </table> </article> <input id="snum"> <input id="sclass">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.