我是jQuery的新手,我想确保我正确地写它。我想开始了解如何尽可能少写。我认为以下应该是.each()函数,但我不确定。这就是我将其编入if语句的原因。
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");
});
}
});
答案 0 :(得分: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]);