2017-01-13 22 views
0

我希望我的網址在頁面加載時顯示在文本字段中。 我試過,但沒有奏效:在頁面加載時在文本字段中插入當前網址

function getUrl() { 
 
    var url = document.URL; 
 
    document.getElementById("textfield").value = url; 
 
}
<input type="text" name="textfield" id="textfield" readonly="true" onload="getUrl()" value="">

+0

嘗試:VAR URL = window.location.href; – darron614

回答

1

The onload attribute will not work on an input element。相反,您可以在窗口上設置偵聽器,以監視頁面何時「加載」。當它被加載,調用該函數:

function getUrl() { 
 
    var url = document.URL; 
 
    document.getElementById("textfield").value = url; 
 
} 
 

 
window.addEventListener('load', getUrl);
<input type="text" name="textfield" id="textfield" readonly="true" value="">

+0

工作,謝謝:)你也許可以向我解釋爲什麼我收到downvote?只是爲了將來的職位,所以我知道我可以做得更好。先謝謝你。 – TomiG

+0

@TomiG,老實說我不太確定。我沒有看到任何具體的原因。必須讓人們對新用戶過度批評。 – KevBot

相關問題