2017-04-18 116 views
0

愚蠢的問題,但我想創建或設置一個圖像src,追加一個字符串後的當前url。如何將當前URL字符串附加到圖像網址只使用Javascript

所以我想編寫

<img src="//testURL.comaction?item={www.currenturl.com}" id="tabUrl" /> 

所以{} www.currenturl.com將當前網址

我知道我可以通過using window.location.href;但如何才能讓當前的URL取代我將它添加到一個字符串?

不知道我是否應該創建一個變量,使用的document.getElementById

taboo = window.location.href; 

應用它或做文檔編寫類似於下面的例子中

<script>document.write('<img src="'//testURL.comaction?item= + 
window.location.href + '">')</script> 

任何幫助表示讚賞。

+2

這兩種方法出了什麼問題?他們不工作嗎? – ceejayoz

回答

1

你的報價是有點過了:當你想要一個純JS的方式做同樣的嘗試這個

'<img src=//testURL.comaction?item=' + window.location.href + '>' 
1

,我建議如下。

var string="testURL.comaction?item="+window.location.href; 
document.getElementsByTagName("img").setAttribute("src", string); 
+0

我用你的例子,沒有改變我的代碼'' – Mariton

相關問題