将Javascript字符串var传递给HTML href标记

Jos*_*ael 5 html javascript variables href

由于限制,我必须在我的网站的每个页眉上设置一个URL字符串作为这样的JavaScript字符串变量 var burl = "http://www.example.com";

现在,我必须将此字符串传递到我网站burl的HTML href=""标记内.我还希望能够在burl旁边的href链接中添加额外的URL元素.

这是完整的代码看起来像Javascript + HTML代码;

<script>
var burl = "http://www.example.com";
</script>
Run Code Online (Sandbox Code Playgroud)
<html>
<head>
</head>
<body>

<h1>JavaScript Variables</h1>

<p>the href below should link to http://www.example.com</p>

<a href="{burl-string-here}/blog/article/">Open Here</a>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

任何帮助解决这个简单的问题将不胜感激.

T.J*_*der 8

你可以用两种方式做到这一点:

  • document.write

  • 通过DOM

document.write:

在您想要链接的脚本标记中:

document.write('<a href="' + burl + '">Open here</a>');
Run Code Online (Sandbox Code Playgroud)

这是在解析页面期间处理的,并用您输出的文本替换脚本链接.

实例:

<script>
var burl = "http://www.example.com";
</script>
<h1>JavaScript Variables</h1>
<p>the href below should link to http://www.example.com</p>
<script>
document.write('<a href="' + burl + '">Open Here</a>');
</script>
<p>this is after the link</p>
Run Code Online (Sandbox Code Playgroud)

通过DOM

在链接上添加一个id:

<a href="" id="burl">Open here</a>
Run Code Online (Sandbox Code Playgroud)

然后在它之后的脚本标记中

document.getElementById("burl").href = burl;
Run Code Online (Sandbox Code Playgroud)

实例:

<script>
var burl = "http://www.example.com";
</script>
<h1>JavaScript Variables</h1>
<p>the href below should link to http://www.example.com</p>
<a href="" id="burl">Open Here</a>
<p>this is after the link</p>
<script>
document.getElementById("burl").href = burl;
</script>
Run Code Online (Sandbox Code Playgroud)


你的评论:

如果......我想手动为每个链接添加一个额外的元素 <a href="burl-string-here/extra-link-element"

我会在链接上使用data-*属性(data-extra无论如何)来说出额外的内容.然后将元素放入变量,然后:

link.href = burl + link.getAttribute("data-extra");`
Run Code Online (Sandbox Code Playgroud)

我不会把额外的东西放进去,href因为有些浏览器尝试扩展,href即使你通过它getAttribute(虽然他们不应该).

你说"每个链接"让我觉得你有很多.如果是这样,请不要使用id,而是使用class:

<script>
var burl = "http://www.example.com";
</script>
<h1>JavaScript Variables</h1>
<p>the href below should link to http://www.example.com</p>
<p><a href="" class="burl" data-extra="/first">First link</a></p>
<p><a href="" class="burl" data-extra="/second">Second link</a></p>
<p><a href="" class="burl" data-extra="/third">Third link</a></p>
<p>this is after the link</p>
<script>
(function() {
  Array.prototype.forEach.call(document.querySelectorAll("a.burl"), function(link) {
    link.href = burl + link.getAttribute("data-extra");
  });
})();
</script>
Run Code Online (Sandbox Code Playgroud)

Array#forEach适用于所有现代浏览器,但不是(比如说)IE8.但它可以是匀化/聚合填充,或者您可以使用简单的for循环.另一个答案中的选项(请参阅"对于类似数组的对象",因为我们从中返回的列表querySelectorAll是类似数组的).