最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery "contains" code doesn't work on chrome - Stack Overflow

programmeradmin4浏览0评论

I'm using this code to check what language is on the site and then remove it from the my dropdown menu. The code works in Firefox but fails to work on chrome and stops all other scripts as well. This is the code:

var mylangme = $(location).attr('href');

if(mylangme.contains("/fr/")){
    mylangme="French";
    $(".subnav li:first-child").css("display","none");
                    }
if(mylangme.contains("/nl/")){
    mylangme="Dutch";
    $(".subnav li:nth-of-type(2)").css("display","none");
                    }
if(mylangme.contains("/ru/")){
        mylangme="Russian";
        $(".subnav li:nth-of-type(3)").css("display","none");
                    }
if(mylangme.contains("/en/")){
        mylangme="English";
        $(".subnav li:last-child").css("display","none");
                    }   

I'm using this code to check what language is on the site and then remove it from the my dropdown menu. The code works in Firefox but fails to work on chrome and stops all other scripts as well. This is the code:

var mylangme = $(location).attr('href');

if(mylangme.contains("/fr/")){
    mylangme="French";
    $(".subnav li:first-child").css("display","none");
                    }
if(mylangme.contains("/nl/")){
    mylangme="Dutch";
    $(".subnav li:nth-of-type(2)").css("display","none");
                    }
if(mylangme.contains("/ru/")){
        mylangme="Russian";
        $(".subnav li:nth-of-type(3)").css("display","none");
                    }
if(mylangme.contains("/en/")){
        mylangme="English";
        $(".subnav li:last-child").css("display","none");
                    }   
Share Improve this question edited Jun 30, 2013 at 7:16 Krista K 21.9k3 gold badges33 silver badges44 bronze badges asked Jun 30, 2013 at 6:48 user2535974user2535974 831 silver badge3 bronze badges 0
Add a comment  | 

2 Answers 2

Reset to default 14

@Quentin is right, you are using a jQuery method on a non-jQuery object. You can fix it using the indexOf method that is part of the standard JavaScript library, and as such is supported by all browsers. The indexOf method will return -1 if the string was not found. Your code would then look like this:

if(mylangme.indexOf("/fr/") != -1) {
    mylangme="French";
    $(".subnav li:first-child").css("display","none");
}

That isn't jQuery. The attr method returns a String, which is core JavaScript.

The contains method for Strings was introduced in JavaScript 1.9 and is only supported by Firefox.

Use indexOf or the polyfill given on the (above linked) MDN documentation page.

发布评论

评论列表(0)

  1. 暂无评论