2

Well this is supposed to be a simple one but have been giving me headache for two days now. I have the following:

<a href="javascript:void();" onclick="return manage(id, value)">Add or remove</a>

The manage function is as follow

function manage(id, param){
    var my_value; 
alert(my_value); // this keeps giving me undefined. I want it to hold the last value of the param

    if(param!=0){ // value not empty, we are removing       
        my_value = remValue(id, param);
    }   
    else if(param==''){ // value is empty, so we are adding 
        my_value = addValue(id, param);
    }   
    alert(my_value);    
}

function addValue(id, param){
    param += 1; 
    return param;

}

function remValue(id, param){
    param -= 1; 
    return param;

}   

The whole idea is to assign the value of param to my_value after the adding or removing operation. Any help please?

4

1 に答える 1

4

var my_value; 関数内で定義することにより、各関数呼び出しで変数を未定義の値に再宣言します。それはその呼び出しに対してのみローカルであり、持続しません。

値を保持するために必要な場合はvar、より高いスコープで宣言する必要があります。

// Declare outside the function...
var my_value;
function manage(id, param){
    alert(my_value); // Should be undefined on first call, 
                     // or hold previous value on subsequent calls after assignment

    if(param!=0){ // value not empty, we are removing       
        my_value = remValue(id, param);
    }   
    else if(param==''){ // value is empty, so we are adding 
        my_value = addValue(id, param);
    }   
    alert(my_value);    
}
于 2012-08-29T18:33:24.013 に答える