这是我之前提出的问题的延伸。原文在这里 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/