簡體   English   中英

如何更改沒有2個菜單項的href?

[英]How to change menu items href without 2 items?

我已更改jQuery菜單項href並帶有檢查網站地址:

    if(window.location.href.indexOf("en") > -1) {
    var link = $('#main-nav a');
        link.each(function(){
    this.href += '-en';
});
    };

它的工作真的很好,但我不想為2個特殊鏈接添加字符串“ -en”。 我該怎么做?

我試圖做這樣的事情,但是不起作用:

 if(window.location.href.indexOf("en") > -1) {
    var link = $('#main-nav a');
        link.each(function(){
            if(link.href === "#special1") || (link.href === "#special2"){
                return this.href;
            } else{
    this.href += '-en';
}
});
    };

您的if語句語法錯誤。 第一個)關閉if表達式。 更改為:

if (link.href === "#special1" || link.href === "#special2") { 

另請注意, href 屬性返回絕對路徑。 您應該使用.getAttribute()方法獲取元素的href 屬性 ,或者讀取錨點的hash屬性。

並且您還應該將link.href更改為this.href

我建議:

var blackList =  ["#special1",  "#special2"];
$('#main-nav a').filter(function() {
    return $.inArray(this.getAttribute('href'), blackList) === -1;
}).prop('href', function(_, href) {
   return href + '-en';
});

另一種選擇是使用.not()方法:

 $('#main-nav a')
      // exclude the elements
     .not('[href="#special1"], [href="#special2"]')
      // update `href` properties
     .prop('href', function(_, href) { return href + '-en'; });

首先,您的if條件存在錯誤。 .href返回絕對路徑,例如http://www.domain.com/yourpage.html#special1 因此,您幾乎沒有辦法做到這一點,如下所示。

if(link.href.indexOf("#special1") !== -1 || link.href.indexOf("#special2") !== -1) {}

if(link.href.match(/\#special[1-2]/i) !== null) {}

if(link.attr("href") === "#special1" || link.attr("href") === "#special2") {}

因此,您的代碼也可以編寫為:

var $links = $('#main-nav a');
$links.filter(function() {
     return this.href.match(/\#special[1-2]/i) === null
}).prop("href", function() {
    return this.href  + "-en";
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM