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

Javascript 动态更改href并链接到url片段,javascript,html,href,document-ready,Javascript,Html,Href,Document Ready,希望有人能帮忙。 我试图动态更改页面上的HREF,然后将用户指向包含以下片段的url: $(document).ready(function(){ if (document.location.pathname.indexOf('cab2') > -1){ document.getElementsByClassName('resourceLink').setAttribute('href','http://www.myserver.net/cab2/#linkReso

希望有人能帮忙。 我试图动态更改页面上的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

  • 或者
  • 然后将相应的HREF设置为:

  • 或者

但是,链接打开的是基本页面(www.myserver.net/cab或cab2),而不是片段页面

我做错了什么?
谢谢你的关心

.getElementsByCassName()
返回一个
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')
    });
});

谢谢@guest271314,虽然仍然无法让它工作,但是你的评论让我开始了。请注意,您的var link语句中有一个小的输入错误,一个额外的结束括号。@RogerW“仍然无法使其工作”当前问题是什么?最后一个正斜杠
/
是否有必要?是的,它仍在加载基本页-www.myserver.net/cab/(或cab2),而不是附加的片段,即www.myserver.net/cab/#linkResources。谢谢你的帮助!感谢您的更新@guest271314,但它仍然无法工作。这可能与我从主页(index.html)上的一个div调用这个函数有关,然后将一个新的html页面加载到index.html并取消隐藏它的内容,即此代码所在的页面实际上是加载到index.html中的about.html。@RogerW
javascript
at-Answer不会出现在链接中?您应该能够在PLNKR上重现问题。如果您正在使用jQuery,请使用它。