如何在没有2个项目的情况下更改菜单项href

How to change menu items href without 2 items?

本文关键字:情况下 菜单项 href 项目 2个      更新时间:2023-09-26

我被jQuery更改了我的菜单项href,并检查了网站地址:

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

它工作得很好,但我不想为两个特殊的链接添加字符串'-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";
});