Javascript 如何通过javascript更改链接HREF

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5785833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:49:52  来源:igfitidea点击:

How to change link HREFs via javascript

javascript

提问by lisovaccaro

I have a form where the user inputs an URL. The value resulting from that input after tweaking it a bit is the variable #url which is displayed to the user right away.

我有一个用户输入 URL 的表单。稍微调整一下后,该输入产生的值是变量#url,它会立即显示给用户。

I need to make the like and tweet buttons in my site point to that URL. Making their HREFS equal to the variable #url

我需要使我网站中的点赞和推文按钮指向该 URL。使他们的 HREFS 等于变量 #url

This are the share buttons:

这是分享按钮:

<a id="twtbutton" href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="theclocktwt">Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div>

<fb:like id="fbbutton" send="false" layout="button_count" width="450" show_faces="false" font="" style="position: absolute; left:110px;"></fb:like>
</div>

Here you can see how it works: http://www.chusmix.com/tests/magic.html

在这里你可以看到它是如何工作的:http: //www.chusmix.com/tests/magic.html

What appears as "Improved link" is the url I want the share buttons to use.

显示为“改进的链接”的是我希望共享按钮使用的网址。

回答by Steve

This is what you want to do -

这就是你想做的——

var yourElement = document.getElementById('yourHref');
 yourElement.setAttribute('href', '#url');

回答by Kyle Rogers

Reference the following page on the jquery site:

参考 jquery 站点上的以下页面:

http://api.jquery.com/attr/

http://api.jquery.com/attr/

Should be able to use attr('href', 'value);

应该可以使用 attr('href', 'value);

回答by Naveed Butt

try this:

尝试这个:

$("#url").keypress(
    function(e) {
        if(e.keyCode == 13) {
            $("#output").attr('href', cleanURL($("#url").val()));
        }
    }
);

回答by Andr3wB

    $('#twtbutton').prop('href', #url);
    $('#fbbutton').prop('href', #url);

This would change the 'href' property of the html element(s) with an id=twtbutton and id=fbbutton to the value stored in #url, where the value stored in #url is a string datatype. This answer utilizes the jQuery library.

这会将 id=twtbutton 和 id=fbbutton 的 html 元素的 'href' 属性更改为存储在 #url 中的值,其中存储在 #url 中的值是字符串数据类型。这个答案使用了 jQuery 库。