簡體   English   中英

在 onclick 之后更改數字顏色的更好方法(功能)是什么?

[英]What would be a better way (function) to change the color of the number after onclick?

我對 JavaScript 還很陌生,並試圖通過迷你項目加深對它的理解。

在這個計數器項目中,我設法得到了我想要的結果:

  • 單擊“添加”按鈕后,計數器增量將增加並變為綠色
  • 單擊“減”按鈕后,計數器增量將減小並變為紅色

下面是我的 JavaScript 代碼:

//create variables to hold the HTML selectors 
var counterDisplay = document.querySelector('.counter-display');
var counterMinus = document.querySelector('.counter-minus');
var counterPlus = document.querySelector('.counter-plus');
//create variable for the counter 
//what we'll use to add and subtract from 
var count = 0;


//create a function to avoid code redundancy 
function updateDisplay(){
  counterDisplay.innerHTML = count;
};

function toGreen(){
  document.querySelector('.counter-display').style.color = "green";
};
function toRed(){
  document.querySelector('.counter-display').style.color = "red";
};

/*-------------------------------------------*/

updateDisplay();

//EventListeners
counterPlus.addEventListener("click", () =>{
  count++;
  updateDisplay();
  toGreen();
});

counterMinus.addEventListener("click", () =>{
  count--;
  updateDisplay();
  toRed();
});

我分離了顏色函數,但我覺得有一種更簡潔的方法來編寫此代碼,即 if 語句之類的條件,但是,由於我仍在學習,我並不完全知道如何實現它。

**如前所述,我仍在學習,因此非常感謝您提供徹底的解釋/外行術語!

請讓我知道任何澄清或是否需要更多信息!

先感謝您!

編輯:感謝那些花時間幫助我分享他們的解決方案的人!

您編寫的代碼很長,但可以完成工作

我不確定你到底想要什么,但這里有一些注意事項:

  • 使用 HTML onclick事件代替:
    您可以在 HTML 代碼中添加它,而不是從 javascript 添加事件偵聽器,如下所示: <button onclick="myFunction()">Click me</button> ,並且每當單擊按鈕時都會調用myFunction()
    您也可以將按鈕作為參數傳遞,例如

 function myFunction(element) { element.style.backgroundColor = "red"; }
 <button onclick="myFunction(this)">Click me</button>

  • 使用let而不是var
    由 var 關鍵字聲明的變量的范圍是立即的 function 主體(因此是 function 范圍),而 let 變量的范圍是由 { } 表示的直接封閉塊(因此是塊范圍)。
    在這里找到更多信息: 使用“let”和“var”有什么區別?

您需要進行以下幾項更改:

  • 利用letconst 如果它將來不會改變它的值,那么使用const else let
  • 您可以創建一個按鈕數組(在下面的示例buttons中),以便您可以循環並在所有按鈕上添加event listener器。 這樣您就不需要在每個按鈕上添加事件偵聽器。
  • 您可以使用data 屬性來識別它是哪種類型的按鈕。
  • 擺脫多個函數toRedtoGreen ,而是制作一個 function ,它只用一個 function changeTextColor來改變文本的顏色。
  • 如果您只需要更改 HTML 元素的文本,那么最好在updateDisplay function 中使用textContent

參見innerText vs innerHTML vs label vs text vs textContent vs outerText

 //create variables to hold the HTML selectors const counterDisplay = document.querySelector(".counter-display"); const counterMinus = document.querySelector(".counter-minus"); const counterPlus = document.querySelector(".counter-plus"); //create variable for the counter //what we'll use to add and subtract from let count = 0; //create a function to avoid code redundancy function updateDisplay() { counterDisplay.textContent = count; } function changeTextColor(color) { counterDisplay.style.color = color; } /*-------------------------------------------*/ //EventListeners const buttons = [counterMinus, counterPlus]; buttons.forEach((btn) => { btn.addEventListener("click", (e) => { const btnType = e.target.dataset.type; if (btnType === "sub") { count--; changeTextColor("red"); } else { count++; changeTextColor("green"); } updateDisplay(); }); });
 .counter-display { background-color: black; padding: 1rem; border-radius: 4px; margin-bottom: 1rem; font-size: 2rem; font-weight: 700; text-align: center; color: whitesmoke; }.button-container { display: flex; gap: 1rem; justify-content: center; }.button-container>* { padding: .75rem 3rem; font-size: 2rem; border: none; border-radius: 4px; }.counter-minus { background-color: red; }.counter-plus { background-color: green; }
 <div class="counter-display"> 0 </div> <div class="button-container"> <button class="counter-minus" data-type="sub">-</button> <button class="counter-plus" data-type="add">+</button> </div>

更多基於應用程序的東西怎么樣? 你可以用一點膠水把你的整個東西分解成幾個關鍵組件,得到一些你可以輕松構建的東西。 它與你已經擁有的並沒有太大的不同,它只是散布着一些經過驗證的真實模式。

 const widget = (element) => { const $minus = element.querySelector('.counter-minus'); const $plus = element.querySelector('.counter-plus'); const $display = element.querySelector('.counter-display'); let state = { color: 'black', count: 0 }; const update = (next) => { state = next; render(); }; const render = () => { $display.innerText = state.count; $display.style.color = state.color; }; const onMinusClick = () => { update({ color: 'red', count: state.count - 1 }); }; const onPlusClick = () => { update({ color: 'green', count: state.count + 1 }); }; $minus.addEventListener('click', onMinusClick); $plus.addEventListener('click', onPlusClick); render(); return () => { $minus.removeEventListener('click', onMinusClick); $plus.removeEventListener('click', onPlusClick); }; }; widget(document.querySelector('#app1')); widget(document.querySelector('#app2')); widget(document.querySelector('#app3'));
 div { margin-bottom: .5rem; }
 <div id="app1"> <button class="counter-minus">-</button> <span class="counter-display"></span> <button class="counter-plus">+</button> </div> <div id="app2"> <button class="counter-minus">-</button> <span class="counter-display"></span> <button class="counter-plus">+</button> </div> <div id="app3"> <button class="counter-minus">-</button> <span class="counter-display"></span> <button class="counter-plus">+</button> </div>

  1. 您可能注意到的第一件事是我的應用程序有多個實例運行。 我可以這樣做,因為我不依賴global state 您可以看到,當您調用小部件時,它擁有自己的變量。

  2. 我有 state 作為 object,唯一可以寫入 state 的是update ZC1C425268E68385D1AB4A70。 你有一些非常相似的東西,除了我將我的 state 合並到一個變量中,並有 1 個 function 負責寫入 state,然后對其做出反應,即渲染。

  3. 然后我附加了一些事件處理程序,它們只是調用更新,他們希望 state 看起來如何。 這當然會觸發渲染以保持 ui 與 state 一致。 這種單向數據流對於保持代碼清晰非常重要。 The update function can be more sophistacted and do things like except partial state values and spread state = {...state, ...next} . 它會變得非常瘋狂。

  4. 最后我返回一個 function。 您可以在此處返回任何內容,您可能希望返回 api 以供用戶與您的小部件進行交互。 例如,您有一個日歷,並且您希望能夠在小部件之外設置日期。 您可能會返回{ setDate: (date) => update({ date }) }或其他內容。 但是我返回了一個 function,它將在小部件之后通過刪除事件偵聽器進行清理,因此垃圾收集可以回收我正在使用的任何 memory。

暫無
暫無

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

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