如何使用jQuery更改超链接的href属性(链接目标)?
当前回答
$("a[href^='http://stackoverflow.com']")
.each(function()
{
this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/,
"http://stackoverflow.com");
});
其他回答
当单击类“menu_link”的链接时,此代码段将调用,并显示链接的文本和url。返回false将阻止链接被跟踪。
<a rel='1' class="menu_link" href="option1.html">Option 1</a>
<a rel='2' class="menu_link" href="option2.html">Option 2</a>
$('.menu_link').live('click', function() {
var thelink = $(this);
alert ( thelink.html() );
alert ( thelink.attr('href') );
alert ( thelink.attr('rel') );
return false;
});
$("a[href^='http://stackoverflow.com']")
.each(function()
{
this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/,
"http://stackoverflow.com");
});
根据您是希望将所有相同的链接更改为其他链接,还是希望仅控制页面给定部分中的链接,或者单独控制每个链接,您可以执行以下操作之一。
更改所有指向谷歌的链接,使其指向谷歌地图:
<a href="http://www.google.com">
$("a[href='http://www.google.com/']").attr('href',
'http://maps.google.com/');
要更改给定节中的链接,请将容器div的类添加到选择器中。此示例将更改内容中的Google链接,但不会更改页脚中的链接:
<div class="content">
<p>...link to <a href="http://www.google.com/">Google</a>
in the content...</p>
</div>
<div class="footer">
Links: <a href="http://www.google.com/">Google</a>
</div>
$(".content a[href='http://www.google.com/']").attr('href',
'http://maps.google.com/');
要更改各个链接而不管它们在文档中的位置,请向链接添加一个id,然后将该id添加到选择器。此示例将更改内容中的第二个Google链接,但不会更改第一个或页脚中的链接:
<div class="content">
<p>...link to <a href="http://www.google.com/">Google</a>
in the content...</p>
<p>...second link to <a href="http://www.google.com/"
id="changeme">Google</a>
in the content...</p>
</div>
<div class="footer">
Links: <a href="http://www.google.com/">Google</a>
</div>
$("a#changeme").attr('href',
'http://maps.google.com/');
在查找时使用attr方法。您可以使用新值关闭任何属性。
$("a.mylink").attr("href", "http://cupcream.com");
Try
link.href = 'https://...'
link.href='https://stackoverflow.com'<a id=“link”href=“#”>单击我</a>
推荐文章
- 使伸缩项目正确浮动
- Babel 6改变了它导出默认值的方式
- 如何配置历史记录?
- ES6模板文字可以在运行时被替换(或重用)吗?
- [Vue警告]:找不到元素
- 可以在setInterval()内部调用clearInterval()吗?
- AngularJS控制器的生命周期是什么?
- 无法读取未定义的属性“msie”- jQuery工具
- 形式内联内的形式水平在twitter bootstrap?
- 我的蛋蛋怎么不见了?
- JavaScript中的排列?
- 自定义元素在HTML5中有效吗?
- JavaScript中有睡眠/暂停/等待功能吗?
- 如何触发自动填充在谷歌Chrome?
- jQuery:执行同步AJAX请求