簡體   English   中英

如何使此功能可重用?

[英]How do I make this function reusable?

如何通過傳遞 2 個參數totalPricecurrentPrice使此函數可重用。

這是代碼(它工作得很好,但我希望它在一個單獨的函數中,以便我以后可以使用它):

$(".btn-quantity").on('click', function () {

    var $button = $(this);
    var oldValue = $button.parent().find("input").val();
    var totalPrice = document.querySelector(".table-price-total"); // I need this querySelector to be the function's first argument
    var currentPrice = document.querySelector(".table-price-current"); // And this the second argument 
    var newVal = parseFloat(oldValue);
    if ($button.hasClass("btn-quantity--plus")) {
      newVal++;
    } else {
      if (newVal - 1 > 0) {
        newVal--;
      }

    }
    let result = newVal * parseFloat(currentPrice.innerHTML);

    totalPrice.innerHTML = result.toFixed(2);

    $button.parent().find("input").val(newVal);

  })

我目前得到的錯誤是: Uncaugh TypeError: $btn.parent is not a function

這是我嘗試過的:

let $btn = document.querySelector(".btn-quantity");
  let btnFunc = (currentPrice, totalPrice) => {
    $btn = document.querySelector(".btn-quantity");
    let oldValue = $btn.parent().find("input").val();
    let cPrice = document.querySelector(currentPrice);
    let tPrice = document.querySelector(totalPrice);
    let newVal = parseFloat(oldValue);
    if ($btn.hasClass("btn-quantity--plus")) {
      newVal++;
    } else {
      if (newVal - 1 > 0) {
        newVal--;
      }
    }

    let result = newVal * parseFloat(cPrice.innerHTML);
    tPrice.innerHTML = result.toFixed(2);
    $btn.parent().find("input").val(newVal);
  }
  $btn.addEventListener('click', (event) => {
    event.preventDefault();
    btnFunc(".table-price-current", ".table-price-total");
  })

通常你會通過使用一個函數來實現其他功能:

function makePriceCalculator(totalPrice, currentPrice) {
  return function() {
    var $button = $(this);
    var oldValue = $button.parent().find("input").val();
    var newVal = parseFloat(oldValue);
    if ($button.hasClass("btn-quantity--plus")) {
      newVal++;
    } else {
      if (newVal - 1 > 0) {
        newVal--;
      }

    }
    let result = newVal * parseFloat(currentPrice.innerHTML);

    totalPrice.innerHTML = result.toFixed(2);

    $button.parent().find("input").val(newVal);
  };
}

那么你發布的例子將被寫成

$(".btn-quantity").on('click', makePriceCalculator(document.querySelector(".table-price-total"), document.querySelector(".table-price-current"));

暫無
暫無

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

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