0

我正在尝试创建对单击的链接做出反应的可折叠 DIV。我找到了如何使用“下一步”执行此操作,但我想将链接放在单独的区域中。我想出了这个可行的方法... JSFiddle - 工程

function navLink(classs) {
this.classs = classs; 
} 

var homeLink = new navLink(".content-home");
var aboutLink = new navLink(".content-about");
var contactLink = new navLink(".content-contact"); 
var lastOpen = null;


$('.home').click(function() {
 if(lastOpen !== null) {
     if(lastOpen === homeLink) {
         return; } else {
    $(lastOpen.classs).slideToggle('fast');
}
 }
   $('.content-home').slideToggle('slow'); 
        lastOpen = homeLink; 
} 
); 


$('.about').click(function() {
if(lastOpen !== null) {
     if(lastOpen === aboutLink) {
         return; } else {
    $(lastOpen.classs).slideToggle('fast');
}
}
   $('.content-about').slideToggle('slow'); 
        lastOpen = aboutLink; 
} 
);  

$('.contact').click(function() {
if(lastOpen !== null) {
     if(lastOpen === contactLink) {
         return; } else {
    $(lastOpen.classs).slideToggle('fast');
}
}
   $('.content-contact').slideToggle('slow'); 
        lastOpen = contactLink; 
}
);​

我现在正在尝试创建相同的结果,但使用单个函数而不是每个链接一个函数。这就是我想出的......

function navLink(contentClass, linkClass, linkId) {
this.contentClass = contentClass;
this.linkClass = linkClass;
this.linkId = linkId;
}

var navs = [];

navs[0] = new navLink(".content-home", "nav", "home");
navs[1] = new navLink(".content-about", "nav", "about");
navs[2] = new navLink(".content-contact", "nav", "contact");

var lastOpen = null;

$('.nav').click(function(event) {

//loop through link objects
var i;
for (i = 0; i < (navsLength + 1); i++) {

    //find link object that matches link clicked
    if (event.target.id === navs[i].linkId) {

        //if there is a window opened, close it 
        if (lastOpen !== null) {
            //unless it is the link that was clicked
            if (lastOpen === navs[i]) {
                return;
            } else {
                //close it
                $(lastOpen.contentClass).slideToggle('fast');
            }
        }

        //open the content that correlates to the link clicked
        $(navs[i].contentClass).slideToggle('slow');

        navs[i] = lastOpen;


    }
 }
 });​

JSFiddle - 不起作用

没有错误,所以我认为我只是做错了。我已经使用 Javascript 大约一个星期了。我已经学习了有关数组和 JQuery 事件的知识,并尝试在此处应用它们。我想我已经走了。想法?谢谢

4

2 回答 2

2

尝试:

var current, show = function(){
    var id = this.id,
        doShow = function() {
           current = id;
           $(".content-" + id).slideToggle('slow');           
        },
        toHide = current && ".content-" + current;

    if(current === id){  //Same link.
        return;   
    }

    toHide ? $(toHide).slideToggle('fast', doShow): doShow();;

};

$("#nav").on("click", ".nav", show);

http://jsfiddle.net/tarabyte/jMzPJ/5/

于 2012-12-05T22:33:34.730 回答
2

您只是忘记定义 navsLength:

var navsLength=navs.length;

当然,您也可以在使用 jQuery 时将其替换为 $()​​.each 循环。

[更新] 我更正的另外两个错误:

lastOpen=navs[i];

for(i=0; i < navsLength ; i++)

演示:http: //jsfiddle.net/jMzPJ/4/

于 2012-12-05T22:35:56.870 回答