javascript - 增强现有的 jQuery 函数以在增量时隐藏 div

标签 javascript jquery

这是我之前提出的问题的延伸。原文在这里 Use existing javascript to trigger if else in php

我创建了一个 fiddle 来进一步解释/展示现有 jQuery 的功能。

我需要的是当 + 按钮将值增加到超过 1 时触发 div 隐藏,因此以某种方式发生事件。

我尝试添加

{ $('#foobar').hide(); }

在数量增加的部分,在这里

$cartAdd.click(function(evt) {
  var $incrementor = jQuery(evt.target)
    , quantity = parseInt($quantity.val(), 10);

但它对我不起作用。

fiddle 在这里 http://jsfiddle.net/Yyb8L/1/

最佳答案

如果我理解正确的话,在单击 #cartAdd 输入时,您需要检查迭代器的值是否已增加到大于 1,然后隐藏 #foobar div。

为此,您首先需要在每次单击“inc”和“dec”按钮时更新该值。

if($incrementor.hasClass('inc')) {
    quantity += 1;
    $quantity.val(quantity);  //the value of $quantity is updated
} else if($incrementor.hasClass('dec')) {
    quantity += -1;
    $quantity.val(quantity); //the value of $quantity is updated
}

其次,您需要将 if/then block 包装在一个函数中,该函数将在输入被单击时调用。

function checkIncrement(){    
    if( $('#cartAdd').find('input').val() > 1 ) 
    { $('#foobar').hide(); }
}

只有在数量更新后才应调用该函数,如下所示:

 $cartAdd.click(function(evt) {
  var $incrementor = jQuery(evt.target)
    , quantity = parseInt($quantity.val(), 10);

  if($incrementor.hasClass('inc')) {
    quantity += 1;
    $quantity.val(quantity); //the value of $quantity is updated
  } else if($incrementor.hasClass('dec')) {
    quantity += -1;
    $quantity.val(quantity); //the value of $quantity is updated
  }

  checkIncrement(); //checkIncrement is invoked after values are updated.

  if(quantity > 0) {
    $quantity.val(quantity);
    xhr.getPrice();
  }


    jQuery(".back").change(function(){
    xhr.getPrice();
    });
});

这是解决方案的 fiddle http://jsfiddle.net/boomish/V7Hnw/1/

希望这有帮助!

编辑以包含正确的 fiddle 链接

关于javascript - 增强现有的 jQuery 函数以在增量时隐藏 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23728398/

相关文章:

javascript - 仅选择未选择的组合框 jquery

javascript - 使用正则表达式选择具有相似 id 的元素 - jquery

javascript - 使用 Jquery 更改单个 'LI' 数组元素的 CSS

jQuery 单击事件在 iOS 中不起作用

javascript - 如何知道 html 片段中的图像在 jquery 的 .load() 之后何时被加载?

javascript - 检查 div 内容是否包含数组中的单词并替换它

javascript - 构建后未显示公共(public)目录中的 React sitemap.xml 文件

javascript - socket.io 不良连接容忍度

javascript - 使用 JavaScript 只允许 HTML 输入中的特定字符

javascript - 在链接的第一个单词后应用样式并插入换行符