在html <a>上使用javascript变量

Ady*_*ari 5 html javascript variables

我有这个javascript代码:

<script ="text/javascript">
    var newUrl=window.location.href;
    var pathArray="";
    pathArray=newUrl.substr(newUrl.lastIndexOf("?")+1);
</script>
Run Code Online (Sandbox Code Playgroud)

我想使用pathArray变量作为标签上href的一部分

这是我的HTML代码

<a href="game.html?"+pathArray>
  <img src="img/RestartButton.png" style="position:absolute;
  left:80px; top:220px">
</a>
Run Code Online (Sandbox Code Playgroud)

但似乎它不读取变量的值,而是它的名称.

tch*_*002 8

您正在将javascript混合到HTML中.

我相信你的pathArray变量也不会包含你期望的内容.

在脚本标记中尝试此操作:

var gamePath = "game.html?" + window.location.search.replace( "?", "" );
document.getElementById("gameAnchor").setAttribute("href", gamePath);
Run Code Online (Sandbox Code Playgroud)

并为您的锚添加一个ID:

<a href="#" id='gameAnchor'>
Run Code Online (Sandbox Code Playgroud)

javascript将从GET当前网址获取所有参数,然后使用您的game.html与网址中的参数连接href的id 替换元素中的属性.gameAnchorGET


Akh*_*ran 1

您不能将 javascript 变量放置在 html 中的任何位置。相反,您需要通过脚本获取 dom 元素并附加 href 属性。给你的锚一个 id 或类名,并尝试这个作为例子。

<a id="myLink" href="game.html">
    <img src="img/RestartButton.png" style="position:absolute;left:80px; top:220px">
</a>

<script type="text/javascript">;
    document.getElementById('myLink').href += window.location.search
</script>
Run Code Online (Sandbox Code Playgroud)