开发者

JavaScript, JQuery Problem: Function triggered automatically when page load!

开发者 https://www.devze.com 2023-03-22 22:03 出处:网络
I\'m a newbie in jQuery, so excuse me for asking such a simple question. I want to use jQuery Spin library and get notified when the value is changing. Here is my code:

I'm a newbie in jQuery, so excuse me for asking such a simple question. I want to use jQuery Spin library and get notified when the value is changing. Here is my code:

<script>
$(document).ready(function(){
    $.spin.imageBasePath = './theme/css/images/spin1/';
    $('#spin1').spin({
        min: 1,
        max: 99,
        lock: true,
        beforeChange: calculate_price()
    });
});

function calculate_price() {
    $('#lblTotalPrice')[0].innerHTML = $('#spin1')[0].valu开发者_如何学Ce;
}
</script>

It's very simple. But the problem is "calculate_price" function is triggered everytime page loaded and it did not trigger when user change the value of Spin Edit.

Does somebody have an idea why this is happening?


I'm not familiar with that particular library, but if you have everything else right, then you need to change this:

beforeChange: calculate_price()

to this:

beforeChange: calculate_price

You were setting beforeChange to the return result from calling calculate_price(), not to the function itself. Thus, it was called once upon initial assignment and not during spin.

Looking at the documentation for the beforeChange callback, you will be getting called before the value actually changes. That callback is called with two parameters, the old and new value so you might want to add those to your calculate_price(newVal, oldVal) function and use them rather than obtaining the value from the spin control.


You should change calculate_price() to calculate_price in spin() method options. The matter is you tried to set to beforeChange field the result of executing calculate_price function. That is why it is called every time on page loaded. You need to set function as callback, so, do not put () after function name.

0

精彩评论

暂无评论...
验证码 换一张
取 消