簡體   English   中英

如何多次使用這些行?

[英]How can I use these lines more than once?

我有3個按鈕。

<button class="one"></button>
<button class="two"></button>
<button class="three"></button>

這是 JS 部分,我的問題不是寫 3 次,而是如何添加一個函數以便我可以根據需要多次使用它? 謝謝你的幫助。

var openBtn = document.querySelector(".one");
var openBtnTwo = document.querySelector(".two");
var openBtnThree = document.querySelector(".three");
var hiddenBox = document.querySelector(".hidden-box");
       
       openBtn.onclick = function(){
    
        if(hiddenBox.style.display ==="none") {
    
            openBtn.innerText = "Close";
            hiddenBox.style.display = "block";
    
        }else {
    
            openBtn.innerText = "Learn More";
            hiddenBox.style.display = "none";
        }
    
       }

openBtnTwo.onclick = function(){
    
        if(hiddenBox.style.display ==="none") {
    
            openBtnTwo.innerText = "Close";
            hiddenBox.style.display = "block";
    
        }else {
    
            openBtnTwo.innerText = "Learn More";
            hiddenBox.style.display = "none";
        }
    
       }

openThree.onclick = function(){
    
        if(hiddenBox.style.display ==="none") {
    
            openThree.innerText = "Close";
            hiddenBox.style.display = "block";
    
        }else {
    
            openThree.innerText = "Learn More";
            hiddenBox.style.display = "none";
        }
    
       }

我的問題不是寫 3 次,而是如何添加一個函數以便我可以根據需要多次使用它? 謝謝你的幫助。

將共享代碼移至函數,並用可應用於所有元素的通用代碼替換特定代碼。 在這種情況下,如果要在單擊時引用每個按鈕,可以使用e.currentTarget

function onClickHandler(e) {
    if (hiddenBox.style.display === "none") {
        e.currentTarget.innerText = "Close";
        hiddenBox.style.display = "block";
    } else {
        e.currentTarget.innerText = "Learn More";
        hiddenBox.style.display = "none";
    }
}

然后為元素添加一個單擊事件偵聽器,如下所示:

openBtn.addEventListener('click', onClickHandler);
openBtnTwo.addEventListener('click', onClickHandler);
openThree.addEventListener('click', onClickHandler);

編輯:我已經刪除了.onclick方法,因為它不應該被使用( ref ),而是使用.addEventListener 正如@Roko C. Buljan 所指出的,我還用e.currentTarget替換了e.target

在您的按鈕中添加另一個類,然后您可以使用 document.getElementsByClassName() 作為數組獲取所有按鈕,然后您可以在數組上運行 foreach 循環

像這樣:-

<button class = "one toggle"</button>
<button class = "two toggle"></button>
<button class = "three toggle"></button>

let toggleButtons = document.getElementsByClassName('toggle')



let yourFunction = ()=>{//wt you want to do on click}

 toggleButtons.forEach(button=>{
        button.onClick=youFunction;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM