【问题标题】:How do I make this function reusable?如何使此功能可重用?
【发布时间】:2020-03-13 14:17:01
【问题描述】:

如何通过传递 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");
  })

【问题讨论】:

  • 这里指的是哪个函数?
  • 您是否尝试过创建函数并将这些值添加为参数?什么不起作用?
  • 如果您仍然使用 jQuery,在我看来,将原生 DOM API 与代码混合在一起会很麻烦。而不是.querySelector(),我只使用等效的jQuery。打字也少了。
  • 您收到错误是因为您的代码只是直接调用您的函数。当 jQuery 调用事件处理函数时,库会确保 this 绑定到所涉及的元素。

标签: javascript function reusability


【解决方案1】:

通常你会通过使用一个产生其他功能的功能来做到这一点:

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"));

【讨论】:

  • 正是...并且该函数将被放置在页面源代码前面某处的<script> 标记中。 (或者您可以制作自己的单独脚本文件...)
猜你喜欢
  • 1970-01-01
  • 2021-12-29
  • 2018-12-23
  • 2021-08-26
  • 2021-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多