代码示例链接:
此代码适用于给定的点击处理程序,$(this) 接受特定类。
我正在尝试获取点击函数中的代码并将其放入它自己的函数中。我想这样做的原因是因为我想根据调用的点击处理程序将 quantity-- 替换为 quantity++ 。我遇到的问题是在函数中调用时变量未定义,因为 $(this) 是窗口。
我很清楚,为了实现我想要的目标,我可能做错了,并且愿意学习更好的方法来实现它。
function price(change) {
return change;
}
$('.cart-item-decrease').click(function(){
price('quantity--');
});
或
$('.cart-item-increase').click(function(){
price('quantity++');
});
最佳答案
您可以自定义事件处理程序注册,以便将其他数据发送到您的函数:
function myClickHandler(e)
{
// ...
quantity += e.data.increment;
// ...
}
$('.cart-item-increase').on('click', null, {
increment: 1
}, myClickHandler);
$('.cart-item-decrease').on('click', null, {
increment: -1
}, myClickHandler);
在这里,increment
属性作为 e.data.increment
发送到 myClickHandler
。
关于javascript - 将值传递给 JQuery 中的函数和变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24708849/