2012-03-07 22 views
0

我有这样的结构:JQuery的DOM孩子的环带复位

<div id="views"> 
    <div id="right-view" class="current-view"> 
    </div> 
    <div id="front-view"> 
    </div> 
    <div id="left-view"> 
    </div> 
</div> 

我要像$(".current-view").next()声明以这样的方式行事,如果“.current视图”被分配给最后一个子(“#左视图“,在这种情况下),第一个孩子被返回(在这种情况下”#右视图“)。

回答

1

你必须自己做,例如:

var next = $(".current-view").next(); 
if (!next[0]) { 
    // No next, use first 
    next = $("#right-view"); 
} 

或者,如果你想避免使用 “右视” id值:

var current = $(".current-view"); 
var next = current.next(); 
if (!next[0]) { 
    // No next, use first 
    next = current.siblings().first(); 
} 

Live example | Live source

$("#theButton").click(function() { 
    var current = $(".current-view"); 
    var next = current.next(); 
    if (!next[0]) { 
     next = current.siblings().first(); 
    } 
    current.removeClass("current-view"); 
    next.addClass("current-view"); 
}); 
-1

这里使用模解决方案:

http://jsbin.com/agasay/edit#javascript,html

$.fn.myNext = function() 
    { 
    var result = $("body p").index($(this))+1; 
    return $("body p").eq(result % $("body p").length ); 

} ; 

    alert($("body p:first").myNext().text()); 
    alert($("body p:first").myNext().myNext().text()); 
    alert($("body p:first").myNext().myNext().myNext().text()); 
+0

*“'如果(!$(this).next())'“*是错误的。 jQuery实例永远不会是假的,这种情况永远不会是真的。 – 2012-03-07 13:34:04

+0

@ T.J.Crowder固定谢谢。 – 2012-03-07 13:35:40

+0

您在地图中使用的功能以及您对地图的使用仍然是错误的。 (该函数在开始时有语法错误。)基本上,你试图太可爱了。 :-) – 2012-03-07 13:42:39

0

这个定义功能getNext()它做你问...

$.fn.getNext = function() { 
    if ($(this).next().length === 0) { 
     return $(this).parent().children().first(); 
    } else { 
     return $(this).next(); 
    } 
} 

$(".current-view").getNext(); 
+0

你可能错过了'返回结果'吗? – 2012-03-07 14:14:31

+0

我在发布之前17分钟编辑了它。你看到一个旧版本。 – Archer 2012-03-07 14:49:50