将值传递给JQuery中的函数和变量作用域 [英] Passing value into function and variable scope in JQuery
问题描述
链接到代码示例:
http:// jsfiddle .net / 99Shr /
此代码适用于给定的点击处理程序,并且 $(this)具有特定的类。
我正在尝试将click函数内部的代码放入它自己的函数中。我想这样做的原因是因为我想用数量++替换数量 - 具体取决于调用哪个点击处理程序。我遇到的问题是,因为 $(this)是window,所以在函数中调用的变量是未定义的。
我很好意识到我可能做错了,以达到我想要的,并且愿意学习更好的方法来实现它。
函数价格(变化){
回报变化;
$ b $('。cart-item-decrease')。click(function(){
price('quantity--');
}) ;
或
$('。cart-item-increase')。click(function(){
price('quantity ++');
});
您可以自定义事件处理程序注册,获得发送到你的函数:
pre $ function myClickHandler(e)
{
// ...
数量+ = e.data.increment; $'
// ...
}
$('。cart-item-increase')。on('click',null,{
increment:1
},myClickHandler); ('click',null,{
increment:-1
},myClickHandler);
$('。cart-item-decrease')。
这里,增量
属性被发送到 myClickHandler
作为 e.data.increment
。
Link to code example:
This code works for a given click handler, and $(this) takes on the particular class.
I am attempting to take the code that is inside the click function and put it into it's own function. The reason I want to do this is because I would like to replace quantity-- with quantity++ depending on which click handler is called. The issue I am running into is that the variables when called in the function are undefined since $(this) is window.
I am well aware that I may be doing this wrong to achieve what I want and am open to learning a better way to achieve it.
function price(change) {
return change;
}
$('.cart-item-decrease').click(function(){
price('quantity--');
});
or
$('.cart-item-increase').click(function(){
price('quantity++');
});
You can customise the event handler registration so that additional data gets sent to your function:
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);
Here, the increment
property gets sent to myClickHandler
as e.data.increment
.
这篇关于将值传递给JQuery中的函数和变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!