Passing value into function and variable scope in

2019-06-08 10:06发布

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条回答
贪生不怕死
2楼-- · 2019-06-08 10:43

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.

查看更多
登录 后发表回答