简体   繁体   中英

jQuery- Why assigning a value to a global variable doesn't work inside a function?

I'm building a slider with 2 buttons to make the number go higher/lower. Here's jsfiddle.

This works:

    var update_num;
    $('.plus').on('click', function() {
         update_num = $('output').text()*1;    
       if (update_num < 100) {
            $('output').text(update_num + 1);
        } else {
            $('output').text(100);
        }
        });

    $('.minus').on('click', function() {
        update_num = $('output').text()*1;          
        if (update_num > 0) {
            $('output').text(update_num - 1);
        } else {
            $('output').text(0);
        }
    }); 

But this doesn't work:

    var update_num = $('output').text()*1;
    $('.plus').on('click', function() {
         if (update_num < 100) {
            $('output').text(update_num + 1);
        } else {
            $('output').text(100);
        }
        });

    $('.minus').on('click', function() {
        if (update_num > 0) {
            $('output').text(update_num - 1);
        } else {
            $('output').text(0);
        }
    }); 

Why is it so, since var update_num is global and all other functions should be able to read it? And what should be the best way to make this code DRY?

The problem here is that the value of update_num is set only once in the second code snippet. For example if its 2. Then every time the minus button is clicked, the value is (2-1) and same way (2+1) when plus button is clicked. The value of update_num should change with every button click.

Your question says why assigning value to global variable doesnt work. But in the second code assignment is never done on button click. Try this:

var update_num = $('output').text()*1;
$('.plus').on('click', function() {
     if (update_num < 100) {
        $('output').text(++update_num);
    } else {
        $('output').text(100);
    }
    });

$('.minus').on('click', function() {
    if (update_num > 0) {
        $('output').text(--update_num);
    } else {
        $('output').text(0);
    }
});

Remember one thing, global variable are dangerous. Say you have initially update_num as 34. So on $('.plus').on('click', function() the value becomes 35. But if you again click, the update_num will not change as it is set only once at var update_num = $('output').text()*1; There is no two way binding which means that if you change $('output').text()*1; the value of update_num will also change You can search google and learn more about the two way binding or the Observable Javascript Pattern .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM