javascript - 防止函数触发

标签 javascript

tl;dr 当字段为空或值为 0 时,此函数默认应用 20% 折扣,如何防止它从一开始就触发?

function longlost() {
  
  var months = parseFloat(document.querySelector('#months').value);
  var finalPrice = (getServicePrice() + extraPrices()) * getDiscountPercent(months);
  document.getElementById("result").value = "€" + finalPrice;
}

我也尝试过,但没有运气:

function longlost() {
  var months = parseFloat(document.querySelector('#months').value);
  if (months.length==0)
   return ;
  var months = parseFloat(document.querySelector('#months').value);
  var finalPrice = (getServicePrice() + extraPrices()) * getDiscountPercent(months);
  document.getElementById("result").value = "€" + finalPrice;
}

最佳答案

// Check for invalid number or number not being positive
if (isNaN(months) || months <= 0) return;

关于javascript - 防止函数触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73961942/

相关文章:

javascript - 如何在文本框中仅获取鼠标所在图像的答案?

javascript - 由另一个函数触发的复选框选择

javascript - handsontable 中的日期格式

javascript:属性名称的数据类型

javascript - 使用自定义响应在谷歌地图上绘制路线

Javascript - 'classes' 数组

javascript - Applescript : click on button with JS

javascript - 无法读取未定义的属性 'match' - PrettyPhoto

javascript - 当我在 html 和 css 中向下滚动时,如何使图像位于菜单栏后面?

javascript - async=true 用于 css 链接标签