2012-11-16 31 views
2

我閱讀問題Scroll to a particular element w/ jQuery並且在問題中,原始HTML代碼已經具有段落元素的ID。但是,就我而言,我動態生成元素(列表元素)並在運行時創建ID。我將如何滾動到具有或不具有jQuery的特定元素?使用動態ID滾動到UL列表中的特定元素

爲了讓我的問題更詳細:

我創建的PhoneGap項目來獲得在iPhone的聯繫人列表,並顯示一個滾動列表(我用的是iscroll插件)在一個div。我將第一個名字A-E,F-J,K-O,P-T,U-Z歸類並分組。如果用戶觸摸側FJ(如你在iPhone聯繫人應用程序找到),股利應滾動到屬於組FJ第一接觸..

<div id ="tablediv"> 
    <div id="scroller"></div> 
</div> 

<div id="sorter"> 
    <span id="gr1">A-E</span> 
    <span id="gr2">F-J</span> 
</div> 

的Javascript:

var g1 = ['a','b','c','d','e']; //contact's first name starting with these chars 
var g2 = ['f','g','h','i','j']; //contact's first name starting with these chars 
var idg1=null, idg2=null; // first id of the contact which was in g1, g2 

//Array is an array of objects 
//example: array = [ {'fname':'x','lname':'y','number':'123'},{..},{..}]; 

function generateTable(array) { 
    gpDiv = document.getElementById("scroller"); 
    pDiv = document.createElement("ul"); 
    pDiv.id = "thelist"; 
    for(var i=0;i<array.length;i++) { 
     cDiv = document.createElement("li"); 
     cDiv.id = 'cd'+i; //id created dynamically 
     cDiv.textContent = array[i].fname+"\u000a"+array[i].lname; 
     var ch0 = array[i].fname[0].toLowerCase(); 
     if($.inArray(ch0,g1)!=-1 && idg1==null) { 
      idg1 = cDiv.id; 
      document.getElementById('gr1').addEventListener('click',function(){goToG1(idg1);},false); 
     } 
     if($.inArray(ch0,g2)!=-1 && idg2==null) { 
      idg2 = cDiv.id; 
      document.getElementById('gr2').addEventListener('click',function(){goToG2(idg2);},false); 
     } 
     pDiv.appendChild(cDiv); 
    } 
    gpDiv.appendChild(pDiv); 
} 

function goToG1(id) { 
    $('#tablediv').scrollTop($('#'+id).offset().top); 
} 

function goToG2(id) { 
    $('#tablediv').scrollTop($('#'+id).offset().top); 
} 

的上面的代碼不起作用,因爲我認爲,因爲id在運行時分配,所以我無法滾動到該特定元素。請幫忙

回答

6

嗯,我需要做的就是這個。

function goToG1(id) { 
    document.getElementById(id).scrollIntoView(); 
} 

在我看來,即使它們在運行時被分配,ID仍然可以工作。

+1

請儘量包括這是如何跨瀏覽器。 :-) – bPratik

+0

我做了一個console.log(document.getElementById(id)),看到有一個方法scrollIntoView()..使用它和中提琴,它的工作! – thandasoru

+0

-1什麼是混亂的方法... pffffff – mate64

0

您代碼工作或多或少 - 但你使用代碼:

$("#tablediv").scrollTop(...) 

而不是

$(document).scrollTop(...) 

除此之外,它的工作原理 - 在這裏看到:http://jsbin.com/umatuj/2/edit

+0

哦,它在我的iOS模擬器中不起作用..我剛纔試過了 – thandasoru

+0

嗯,或許有些東西與iOS處理這些代碼有關(因爲它在常規瀏覽器(鉻))。無論如何,你已經發布了適合你的解決方案,所以它很好。 – WTK