【发布时间】:2012-11-16 16:58:35
【问题描述】:
我阅读了 Scroll to a particular element w/ jQuery 问题,在该问题中,原始 HTML 代码已经具有段落元素的 ID。但是,就我而言,我动态生成元素(列表元素)并在运行时创建 ID。使用或不使用 jQuery,我将如何滚动到该特定元素?
要详细说明我的问题:
我正在创建一个 phonegap 项目来获取 iPhone 中的联系人列表并在 div 中显示滚动列表(我使用 iscroll 插件)。我对名字 A-E、F-J、K-O、P-T、U-Z 进行分类并将它们分组。如果用户在侧面触摸 F-J(如您在 iPhone 联系人应用程序中找到的那样),则 div 应该滚动到属于组 F-J 的第一个联系人..
<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 是在运行时分配的,所以我无法滚动到该特定元素。请帮忙
【问题讨论】:
标签: javascript jquery cordova scroll