2010-09-28 60 views
1

我想我很想念一些邏輯洞察力。這似乎很容易,但我只是沒有看到它..列表順序的邏輯問題

我有一個列表,並希望看到是否有列表項目單擊項目之前和/或之後。下面的代碼


<script> 
[..] 
$("a").click(function(event){ 
var parentEl = $(this).closest("ul"); 
var currPosition = $(this).parent().prevAll().length + 1; 
var totalItems = $("#"+$(parentEl).attr("id")+" li").length; 

if(currPosition == totalItems){ alert("Previous and Next"); } 
if(currPosition <= totalItems){ alert("Next"); } 
if(currPosition >= totalItems){ alert("Previous"); } 
[..] 
</script> 

[..] 

<ul id="listOne"> 
<li><a>Text 1</a></li> 
<li><a>Text 2</a></li> 
<li><a>Text 3</a></li> 
<li><a>Text 4</a></li> 
</ul> 

上面的代碼幾乎只能一個我單擊最後一個項目,一切都被驚動了.. 我只是想知道,如果有一個上一個,下一個或上列表項這兩個opions點擊

回答

1

快速修復:

if(currPosition == totalItems){ 
    alert("Previous"); 
} else if(currPosition == 1){ 
    alert("Next"); 
} else { 
    alert("Previous and Next"); 
} 
+0

地獄般簡單!我就知道!謝謝! – Maurice 2010-09-28 14:51:05

0

您可以檢查使用.nextAll().prevAll().length,像這樣:

$("a").click(function(event){ 
    var pCount = $(this).closest('li').prevAll().length, //how many previous 
     nCount = $(this).closest('li').nextAll().length; //how many after 
    if(pCount > 0 && nCount > 0){ alert("Previous and Next"); } 
    else if(nCount > 0){ alert("Next"); } 
    else if(pCount > 0){ alert("Previous"); } 
}); 

You can give it a try here,當然你也可以讓這個短得多,但試圖ILLU這個方法可以告訴你不僅以前/以下的元素,如.prev().next()會,但是多少,如果有什麼關係的話。

1

讓你的生活變得更輕鬆一些,並使用index()找到某物的當前位置。

$("a").click(function() { 
    var li = $(this).closest("li"); 
    var items = li.parent().children(); 
    var currPosition = items.index(li); 
    var totalItems = items.length(); 
    if (currPosition == 0) { 
    // first 
    } else if (currPosition == totalItems.length - 1) { 
    // last 
    } else { 
    // middle 
    } 
}); 

或者,你可以做測試是這樣的:

if (li.is(":first-child")) { 
    // first 
} else if (li.is(":last-child")) { 
    // last 
} else { 
    // in the middle 
} 
+0

也可以做'li.index()'(假設jQuery的1.4或更高版本)。 – user113716 2010-09-28 14:40:33

0

一個簡單的,如果他們是前或父李之後的項目檢查的情況。

$("a").click(function(){ 
     var itemsBefore = ($(this).parent().prev().length>0) 
     var itemsAfter = ($(this).parent().next().length>0) 
     if(itemsBefore && itemsAfter) alert("Previous and next"); 
     else if(itemsBefore) alert("Previous"); 
     else alert("Next"); 
    }); 

工作小提琴這裏 - >http://jsfiddle.net/wmgvB/