0

マスターページにメニューがあります。

 <ul>
    <li><a href="."><span>Home</span></a></li>
    <li><a href="contactus.aspx"><span>contact us</span></a></li>
 </ul>

メニュー項目をクリックすると、jqueryを使用してcssクラスを設定したい

 $(function () {

            $("li:first-child").addClass("test");
            $('li').click(function () {
                $(this).addClass('test');

            });
        });

css

 .test {background-color:Red;}

メニューをクリックすると、背景色が表示されますが、その後消えます。別のメニューがクリックされるまでアクティブのままにするにはどうすればよいですか?

ありがとうございました

4

2 に答える 2

3

UPDATE2: this is not a javascript problem

<li><a href="#"><span <%=ServerSizeLogic.SelectedMenu("Home")%>>Home</span></a></li>

This is a nasty guess on how the server side might to it, depending on your server side technology. ServerSizeLogic.SelectedMenu("Home") or whatever you use would either return an empty string or "class='test'". Just make sure only one of your li elements gets the style and remove the client side code

// don't do it like this but hopefully you get the gist
ServerSizeLogic::SelectedMenu(string item){
    if (item == CurrentPage)
      return "class='test'";
    return "";
}

UPDATE: obviously once you navigate away from the page the element you want to be selected will have to come from the server (unless you are using ajax), in which cast just get rid of the li:first-child and set the class directly in your view code on the current li element

Original: How about this little fiddle http://jsfiddle.net/LmUrP/

 $(function () {

        $("li:first-child").addClass("test");
        $('li').click(function () {
            $('#menu li').removeClass('test');
            $(this).addClass('test');
        });
    });​

html

<ul id='menu'>
  <li><a href="#"><span>Home</span></a></li>
  <li><a href="#"><span>contact us</span></a></li>
  <li><a href="#"><span>apples</span></a></li>
  <li><a href="#"><span>bananas</span></a></li>
</ul>​
于 2012-08-13T21:46:34.460 に答える
1

これにより、現在のページの URL に基づいて「現在のリスト項目」を強調表示できるようになります
。読み込み時に URL をテストする必要があります。

$(function () {
    $('ul#menu>li>a[href="'+location.pathname+'"]').addClass('test');      
});​

あなたのhtmlを次のようにしてください:

<ul id="menu">
    <li><a href="/"><span>Home</span></a></li>
    <li><a href="/contactus.aspx"><span>contact us</span></a></li>
</ul>

/href 属性値の先頭にあることに注意してください。location.pathnameこれは、常に絶対パスを返すためです。

ここにフィドルがありますhttp://jsfiddle.net/unloco/29E23/
私が書いhref="/_display/"たのは、それが jsfiddle の表示 iframe の URL だからです!

しかし、あなたのページが入っている場合は、正しい動作をさhttp://domain.com/folder/page.phpせるために書く必要があります!href='/folder/page.php'

于 2012-08-13T21:51:34.003 に答える