繁体   English   中英

动态更改href并链接到url片段

[英]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

但是,链接会打开基页(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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM