簡體   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