简体   繁体   中英

Javascript: change variable inside a function?

How to change an variable inside a function? I trying to archive an simply toggle function based on one preassigned value. Here the code and here http://jsfiddle.net/StartStep/jLQyx/

<p onclick="testit()">CLick</p>
<p id="value">Value</p>   


var valuediv = document.getElementById("value");

function testit() {
    if (c == 1) {
        var c = 1;
        valuediv.innerHTML = c
    } else {
        var c = 0;
        valuediv.innerHTML = c
    }
}

Have a look at how JavaScript uses Global Variables here.

var valuediv = document.getElementById("value");
var c = 1;

function testit() {
    if(c === 1) 
    {
        c = 0; 
        valuediv.innerHTML = c
    } else {
        c = 1; 
        valuediv.innerHTML = c
    }
}

This fixes your code. You were creating new "c" variables in your if/else blocks due to prefixing them with "var".

Fiddle: http://jsfiddle.net/jLQyx/2/

Remove var keyword and write c = 1 & c = 0 . You're re-creating variable c inside the function instead of updating the global c variable.

var valuediv = document.getElementById("value");
var c = 1;

function testit() {
    if (c == 1) {
        c = 0;
        valuediv.innerHTML = c;
    } else {
        c = 1;
        valuediv.innerHTML = c;
    }
}

http://jsfiddle.net/jLQyx/1/

No need to use conditionals:

var valuediv = document.getElementById("value"),
    c = 1;
function testit() {
    c = +!c;
    valuediv.innerHTML = c
}

Demo

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