使用JS和HTML将当前URL插入链接

7

所以,我已经阅读了类似的文章,但仍然找不到更符合我所做的事情的答案。我正在尝试使用JS获取当前页面的URL,并将其附加到社交媒体共享链接中,如下所示:

<a href="http://reddit.com/submit?url=CURRENTPAGE.html; title="This is a post!" target="_blank">

使用Javascript,我已经成功将当前URL分配给一个变量:
<script>
var x = window.location.href;
document.getElementById("smsharing").innerHTML = x;
</script></p>

我通过测试显示来确保它有效。那么,实际上将“x”放在CURRENTPAGE.html的位置的正确方法/语法是什么?

我知道这是一个愚蠢的问题,但我真的很困惑。具体细节会有所帮助,因为问题的一部分是我对JS知之甚少。你有什么想法吗?

7个回答

3

获取当前元素的 href 属性,如果其值不是 url,则将当前 URL 添加到其中。

修改后的 HTML

<a id='smsharing' 
   href="http://reddit.com/submit?url="
   title="This is a post!"
   target="_blank">link</a>

脚本

<script>
var x = window.location.href;
var link = document.getElementById("smsharing"); // store the element
var curHref = link.getAttribute('href'); // get its current href value
link.setAttribute('href', curHref + x);
</script>

3
这应该可以解决问题:
<script>
baseurl="http://www.facebook.com?"
function buildURL(item)
{
    item.href=baseurl+window.location.href;
    return true;
}
</script>
</head>
<body>
<a onclick="return buildURL(this)" href="">Google</a>
</body>

2

仅使用纯JavaScript,您可以通过将基本href设置为字符串,然后在需要的任何地方添加变量来设置链接的href。

var x = window.location.href;
document.getElementById("linkid").href = "http://reddit.com/submit?url="+encodeURIComponent(x);

当然,你可能想将 x 附加为查询字符串参数时使用 encodeURIComponent(x) 而不是仅使用 x - Thriggle

1
使用jQuery非常简单,只需要这样:
$('a').attr("href",x);

0
一旦您可以访问当前URL,您就想找到该元素并替换CURRENTPAGE.html。为此,您需要一种选择该元素的方法。我们给它一个ID:
<a id="myLink" href="http://reddit.com/submit?url=CURRENTPAGE.html"></a>

现在我们可以这样获取链接:

var link = document.getElement('myLink');

让我们再次获取URL,并给它一个更好的变量名:

var url = window.location.href;

现在,让我们更新 link 的 HREF 属性:
link.href = link.href.replace('CURRENTPAGE.html', url);

就是这样了!


0
你只需要将 innerHTML 替换为 href
document.getElementById("smsharing").href = x;

希望这能有所帮助。

0

为您的链接创建另一个变量来存储完整的href属性:

var myURL = "http://reddit.com/submit?url=" + x;

然后使用该变量替换当前的href属性:

docment.getElementById("YourLinkTagID").href = myURL


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接