简体   繁体   English

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

[英]Dynamically change href and link to a url fragment

Hope someone can help. 希望有人能提供帮助。 I'm trying to dynamically change hrefs on a page and then point the user to a url which includes a fragment as: 我正在尝试动态更改页面上的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');
        };
});

In the HTML I'm using several links like this: 在HTML中,我使用了以下几个链接:

<a class="resourceLink" href="" title="Link to Resources section" target="_blank">Resources</a>

What I was hoping for was the script would check what url the visitor had used to arrive at the site, either 我希望的是脚本会检查访问者用来到网站的URL

What happens though is the link opens up the base page (www.myserver.net/cab or cab2) and not the #fragment page. 但是,链接会打开基页(www.myserver.net/cab或cab2),而不是#fragment页面。

What am I doing wrong? 我究竟做错了什么? My thanks for your interest. 谢谢你的兴趣。

.getElementsByClassName() returns an HTMLCollection , not a single element. .getElementsByClassName()返回HTMLCollection ,而不是单个元素。 You can use .each() to iterate all .resourceLink elements, .attr() to set href attribute value 您可以使用.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