2017-04-18 63 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

相关问题