Passing value into function and variable scope in JQuery

限于喜欢 提交于 2019-12-23 02:48:12

问题


Link to code example:

http://jsfiddle.net/99Shr/

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++');
});

回答1:


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.



来源:https://stackoverflow.com/questions/24708849/passing-value-into-function-and-variable-scope-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!