0

I want to loop through an array in order to add CSS to menu links with jQuery. If a certain string appears in the URL, a certain CSS is assigned to a menu link that contains the same string.

Here's HTML (not sure if it really helps, but here it is):

<ul>
    <li>
        <a href="http://mysite.com/">HOME</a>
        <a href="http://mysite.com/about">ABOUT</a>
        <a href="http://mysite.com/brands">BRANDS</a>
        <a href="http://mysite.com/investors">INVESTORS</a>
        <a href="http://mysite.com/news">NEWS</a>
        <a href="http://mysite.com/videos">VIDEOS</a>
        <a href="http://mysite.com/contact">CONTACT</a>
    </li>
</ul>

Here's my code snippet:

var url_link = new Array();

url_link[0] = 'about';
url_link[1] = 'the-company';
url_link[2] = 'employment';
url_link[3] = 'customer-service';
url_link[4] = 'faqs';
url_link[5] = 'brands';
url_link[6] = 'news';
url_link[7] = 'videos';
url_link[8] = 'contact';

for (var i=0; i<url_link.length; i++) {
    if (location.href.indexOf(url_link[i])>=0) {
        $('.appearance-menus-'+url_link[i]+'>a').css("color", "#636363");
        $('.appearance-menus-'+url_link[i]+'>a').mouseout(function() {
            $(this).css("color", "#636363");
        });
    }
}

For some reason, this snippet breaks the website, and I suspect it's the problem of concatenating an array element into the jQuery selector. I must have messed up the syntax.

What is the proper way to do that?

4

2 回答 2

1

您编写的代码没有什么特别的问题,它应该可以将内联样式添加到选定的链接。

您正在生成的选择器如下:

'.appearance-menus-about > a'
'.appearance-menus-the-company > a'
'.appearance-menus-employment > a'
'.appearance-menus-customer-service > a'
'.appearance-menus-faqs > a'
'.appearance-menus-brands > a'
'.appearance-menus-news > a'
'.appearance-menus-videos > a'
'.appearance-menus-contact > a'

您可能希望确保这些存在于您的文档中。

最后,我冒昧地写了一个更高效的版本:

var url_links = [
        'about',
        'the-company',
        'employment',
        'customer-service',
        'faqs',
        'brands',
        'news',
        'videos',
        'contact'
    ],
    links = url_links.filter(function (val, index, arr) {
        return location.href.toLowerCase().indexOf(val.toLowerCase()) > -1;
    }),
    link = '';
for (i = 0; i < links.length; i += 1) {
    link = links[i];
    selector = '.appearance-menus-' + link + ' > a';
    console.log(selector);
    $(selector).mouseout(function() {
        $(this).css('color', '#636363');
    }).trigger('mouseout');
}
于 2013-06-18T15:55:17.843 回答
1

因为indexOf不是跨浏览器功能,您应该使用替代方法(例如使用http://www.w3schools.com/jsref/jsref_search.asp)或自己实现它:How to fix Array indexOf() in JavaScript for Internet Explorer 浏览器

于 2013-06-17T14:31:45.607 回答