2017-06-13 48 views
0

我在網頁上有一個文本框。我想知道URL的散列值,例如12345並將其作爲文本框的值加載頁面(如果有值),否則,我希望文本框保持空白。使用純JavaScript預填一個帶有網址哈希的文本框

我已經使用這個代碼的嘗試:

var hash = window.location.hash.substr(1); 

function onoff(){ 
// pre-fill chat id textbox 
    if(hash){ 
    var hash_value = window.location.hash.replace('#',''); 
    document.getElementById("chat").value = hash_value; 
    } else { 
    document.getElementById("chat").value = ''; 
    } 
} 

而在HTML代碼(我有在調用該函數的麻煩)。

<input type="text" id="chat" maxlength="5" required=""> 

如果我要改變散列的值,是否有可能在加載時填充文本框?

+0

窗口.onload = ONOFF(); – Liquidchrome

回答

0

當然可以!只需通過你的功能window.onload

var hash = window.location.hash.substr(1); 

window.onload = function onoff(){ 
// pre-fill chat id textbox 
    if(hash){ 
    var hash_value = window.location.hash.replace('#',''); 
    document.getElementById("chat").value = hash_value; 
    } else { 
    document.getElementById("chat").value = ''; 
    } 
} 

<input type="text" id="chat" maxlength="5" required=""> 

希望這有助於! :)

0

DOMContentLoaded上執行您的功能。請注意,此功能可被限於此:

function onoff(){ 
    document.getElementById("chat").value = window.location.hash.substr(1); 
} 

document.addEventListener("DOMContentLoaded", onoff); 

要也捕獲到散列純變化(在這種情況下,頁面不重新加載),也捕捉對應hashchange事件:

window.addEventListener("hashchange", onoff);