2012-02-24 2 views
0

jQueryは非常に新しく、正しく書いていますか?できるだけ少ない書き方を理解していきたいと思っています。私は、次のような.each()関数にする必要がありますが、私はよく分かりません。だから私はそれをif文にコーディングするのです。Jqueryをシンプルにする方法を理解しようとしています

HTML

  <div id="header" class="container"> 
      <div class="row"> 
      <div class="sixcol"> <a href="#"><img src="http://dermdev3/sites/Dermatology/images/logo/derm_header_penn_logo.png" alt="Penn Medicine - Dermatology Header Logo" name="logo" width="363" height="103" id="logo"></a></div> 
      <div class="sixcol last"> 
       <ul id="navigation"> 
       <li><a class="navy" href="#" title="Home">Home</a></li> 
       <li><a class="red" href="#" title="Link">Link</a></li> 
       <li><a class="yellow" href="#" title="Link">Link</a></li> 
       <li><a class="light-blue" href="#" title="Link">Link</a></li> 
       </ul> 
      </div> 
      </div> 
     </div> 

のjQuery

$(function() { 
//Webpages 
var home = "Home.hmtl"; 
var wiki = "Wiki.html"; 

//Main Navigation 
var header = $("div#header"); 
var colors = "navy red yellow light-blue"; 
var nav = $("#navigation"); 
var navList = $("#navigation li"); 

if (pathname == wiki) { 
    header.addClass("red"); 
    $("#navigation a.red").attr("id", "current"); 

    navList.children().mouseenter(function() { 
     $("#navigation a.red").removeAttr("id", "current"); 
    }); 

    nav.mouseleave(function() { 
     header.removeClass(colors).addClass("red"); 
     $("#navigation a.red").attr("id", "current"); 
    }); 
} 
if (pathname == home) { 
    header.addClass("navy"); 
    $("#navigation a.navy").attr("id", "current"); 

    navList.children().mouseenter(function() { 
     $("#navigation a.navy").removeAttr("id", "current"); 
    }); 

    nav.mouseleave(function() { 
     header.removeClass(colors).addClass("navy"); 
     $("#navigation a.navy").attr("id", "current"); 
    }); 
} 

})。

答えて

1
var pages = { 
    "Wiki.html": { 
     "className": "navy", 
    }, 
    "Home.html": { 
     "className": "red" 
    } 
    // add other pages here. 
}; 

var header = $("div#header"); 
var colors = "navy red yellow light-blue"; 
var nav = $("#navigation"); 
var navList = $("#navigation li"); 

function configure(page){ 
    var anchors = function(){ 
     return nav.find("a."+page.className); 
    } 
    header.addClass(page.className); 
    anchors().attr("id", "current"); 

    navList.children().mouseenter(function() { 
     anchors().removeAttr("id", "current"); 
    }); 

    nav.mouseleave(function() { 
     header.removeClass(colors).addClass(page.className); 
     anchors().attr("id", "current"); 
    }); 
} 

そして、それを呼び出す:

configure(pages[pathname]); 
+0

うわー!どうもありがとうございます!どのように私はそれを呼び出すだろうか?覚えている私はまだ学んでいる:) – Davis

+0

よく、それは異なります。ユーザーが何かをやった後、いつページを呼び出すか、ページが読み込まれますか? – ggreiner

+0

ページが読み込まれます。 – Davis

関連する問題