簡體   English   中英

為什么這些全局變量在3個函數之間消失?

[英]Why do these global variable vanish between 3 functions?

我有三個函數,對於此示例,它們按以下順序觸發:

function editmatch(){
        defaultstyling();
        $('.all_cons').css({display: 'none'});
        $('.confirm_button'+id).css({display: 'inline'});
        storecontents();
        isediting = true;
        $(document).find("td[id^='hero_column"+id+"']").html('<input id="select_hero" type="text" name="select_hero">');
        $(document).find("td[id^='result_column"+id+"']").html("<select name='winloss'><option value='Win'>Win</option><option value='Loss'>Loss</option></select>");
        $(document).find("td[id^='gamemode_column"+id+"']").html('<select name="gamemode"<option value="All Pick">All Pick</option><option value="Captains Mode">Captains Mode</option><option value="Captains Draft">Captains Draft</option></select>');
        $(document).find("td[id^='mmr_column"+id+"']").html('<input id="input_mmr" type="text" name="input_mmr">');
}

摘要:函數將單元格內的文本更改為“表單”(仍不完整)。 在更改單元格內部的文本之前,將storecontents()函數。 在這里:

function storecontents(){   //HOLDS CONTENTS OF ROW
    var herotemp = document.getElementById("hero_column"+id).innerHTML;
    var resulttemp = document.getElementById("result_column"+id).innerHTML;
    var gametemp = document.getElementById("gamemode_column"+id).innerHTML;
    var mmrtemp = document.getElementById("mmr_column"+id).innerHTML;
    alert(herotemp);
}

此函數在更改文本之前將文本存儲在單元格中。 請注意,這些變量是在我的編碼頁面的頂部全局定義的。 此警報將herotemp顯示為以前的html:“ Rubick”。

然后,一個按鈕觸發該代碼(如果需要)以將內容更改回原始內容:

function abandonedit(){
       alert(herotemp);
       $(document).find("td[id^='hero_column"+id+"']").html(herotemp);
        $(document).find("td[id^='result_column"+id+"']").html(resulttemp);
        $(document).find("td[id^='gamemode_column"+id+"']").html(gametemp);
        $(document).find("td[id^='mmr_column"+id+"']").html(mmrtemp);
}

但是,上述功能中的警報顯示herotemp變量(和所有其他變量)為空。 我以為全局聲明的變量可以在所有函數中使用? 我做錯了什么還是我誤會了?

如果在函數內部使用var ,則僅此函數內部聲明此變量。 同樣,如果您有一個變量聲明為global且名稱相同。

生成全局變量或使用全局變量,只需刪除var

如果您在var herotemp聲明變量var herotemp ,則會有一個名為herotemp的局部(函數范圍)變量,該變量將阻止您訪問全局變量herotemp

這應該將您的代碼固定為預期的行為。

function storecontents(){   //HOLDS CONTENTS OF ROW
    /*var*/ herotemp = document.getElementById("hero_column"+id).innerHTML;
    var resulttemp = document.getElementById("result_column"+id).innerHTML;
    var gametemp = document.getElementById("gamemode_column"+id).innerHTML;
    var mmrtemp = document.getElementById("mmr_column"+id).innerHTML;
    alert(herotemp);
}

有時候,您需要一個名為x的局部(函數范圍)變量以及一個名為x的全局變量。 為此,您必須執行以下操作:

var x = 3;

function useX() {
    var x = 5;
    alert(x, window['x']);
}

要么:

var x = 3;

function useX(x) {
    alert(x, window['x']);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM