[英]Dynamically change href and link to a url fragment
希望有人能提供帮助。 我正在尝试动态更改页面上的href,然后将用户指向包含片段的url:
$(document).ready(function(){
if (document.location.pathname.indexOf('cab2') > -1){
document.getElementsByClassName('resourceLink').setAttribute('href','http://www.myserver.net/cab2/#linkResources');
} else {
document.getElementByClassName('resourceLink').setAttribute('href','http://www.myserver.net/cab/#linkResources');
};
});
在HTML中,我使用了以下几个链接:
<a class="resourceLink" href="" title="Link to Resources section" target="_blank">Resources</a>
我希望的是脚本会检查访问者用来到网站的URL
http://www.myserver.net/cab2/然后将适当的href设置为:
但是,链接会打开基页(www.myserver.net/cab或cab2),而不是#fragment页面。
我究竟做错了什么? 谢谢你的兴趣。
.getElementsByClassName()
返回HTMLCollection
,而不是单个元素。 您可以使用.each()
迭代所有.resourceLink
元素, .attr()
来设置href
属性值
$(document).ready(function(){
var link = document.location.pathname.indexOf('cab2') > -1 ? "cab2" : "cab";
$('.resourceLink')
.each(function() {
$(this)
.attr('href','http://www.myserver.net/'+ link +'#linkResources')
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.