2011-07-20 58 views
0

我正在爲我的網站編寫留言板。每條消息都通過數據庫中的自動增量獲取一個id。板上的信息在「li id =#」標籤下,「li」從數據庫中獲取id。我試圖通過JavaScript創建滾動功能,以便向下和向上的箭頭可以移動整個消息。通過#id滾動div,我做錯了什麼?

這是我到目前爲止有:

down.node.onclick = function() { // down arrow 

var msgs = document.getElementById("kommentit"); // the <ul> element 
var a = new Array(); 


if (msgs.hasChildNodes()) { 
    var children = msgs.childNodes; 
    for (var i = 0; i < children.length; i++) { 
     if (msgs.childNodes[i].tagName == "LI") { 
      a.push(msgs.childNodes[i].id); // array with the id's 
     } 
    } 

} 

for (var i = 0; i < a.length; i++) { // this is what goes wrong 
    parent.location.href = '#' + 'a[i + 1]'; 
} 

因此,儘管陣列得到正確的價值觀的實際功能不起作用。使用這段代碼,當我點擊時,我得到.../index.php#[a + 1]作爲我的url。

如果我使用''+ a [i + 1] +'',頁面會刷新整個數組,直到使用#undefined解決。

id的格式爲「id-xx」,那麼問題出在哪?我嘗試通過使用msgs.childNodes [i] .id.split(「id-」)來分割id,但是如果我這樣做,則會在數組中獲得「,xx」作爲我的值。

回答

1

如果你希望每次有時間滾動到下一個項目追查您滾動到最後一個項目。 不要發明自行車,我建議你使用一些JS框架和插件進行滾動。它會爲你節省很多時間。

的例子是:

+0

夠公平,看起來可以工作。謝謝! –

1

嘗試

down.node.onclick = function() { // down arrow 

var msgs = document.getElementById("kommentit"); // the <ul> element 
var a = new Array(); 


if (msgs.hasChildNodes()) { 
    var children = msgs.childNodes; 
    for (var i = 0; i < children.length; i++) { 
     if (msgs.childNodes[i].tagName == "LI") { 
      a.push(msgs.childNodes[i].id); // array with the id's 
     } 
    } 

} 

for (var i = 0; i < a.length; i++) { // this is what goes wrong 
    parent.location.href = '#' + a[i]; 
} 
+0

與''+ a [i + 1] +''相同,它會遍歷整個數組,然後使用#undefined處理。 (和位置去最後一個實際值) –

+0

你可以把一個例子jsfiddle.net? – Fender

+0

http://pohjis.site40.net/testi.php你可以在那裏找到它,但只有向下箭頭功能 –

0

你爲什麼要加1數組的索引?

你試過:

for (var i = 0; i < a.length; i++) { // this is what goes wrong 
    parent.location.href = '#' + a[i]; 
} 

但我可能會使用jquery(或類似)這樣的事情,因爲更改URL像上面添加的東西加載到用戶的歷史記錄,並打破了回來按鈕。

+0

啊,是的,再次是同樣的交易,所以它滾動了整個事情。感謝您的反饋,我想我正在嘗試jCarousel之前提出的建議。這裏是一位新手,這是我第一次編程,因此一直都在學習。 –