使用屏幕加载打开 javascript,然后单击

Have javascript toggled on with screen load, and then with click

我有一个具有脚本功能的菜单,在该菜单中单击会切换到 link 的不同背景颜色,直到单击另一个 link:

    $(function() {
       $(".button").click(function() {
         $(this).css('background-color', '#555');
         $(".button").not($(this)).css('background-color', '');

       });
    });

我想要这个link:

    <a class="button main" href="background.html">Main</a>

在页面加载时切换背景颜色,但保留以前的切换功能。

这是 HTML 的其余部分:

    <a class="button main" href="background.html">Main</a>
    <a class="button" href="text-1.htm">Text 1</a>
    <a class="button" href="text-2.htm">Text 2</a>
    <a class="button" href="text-3.htm">Text 3</a>
    <a class="button" href="text-4.htm">Text 4</a>
    <a class="button" href="text-5.htm">Text 5</a>
    <a class="button" href="text-6.htm">Text 6</a>
    <a class="button" href="text-7.htm">Text 7</a>
    <a class="button" href="text-8.htm">Text 8</a>
    <a class="button" href="text-9.htm">Text 9</a>
    <a class="button" href="text-10.htm">Text 10</a>
$(function(){
    $('.main').css('background-color', '#555');

    $(".button").click(function() {
        $(this).css('background-color', '#555');
        $(".button").not($(this)).css('background-color', '');
    });
});

您可以在文档准备好后简单地将样式放在 main 上。

更好的选择:

CSS

.main { background: #555 }

JS

$(function(e){
    e.preventDefault();
    $(".button").click(function(){
        $(this).parent().find('.main').removeClass('main');
        $(this).addClass('main');
    });
});

JSFIDDLE:https://jsfiddle.net/rv68enu6/