使用动态ID滚动到UL列表中的特定元素

时间:2012-11-16 08:29:08

标签: javascript jquery cordova scroll

我阅读了问题 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是在运行时分配的,所以我无法滚动到该特定元素。请帮忙

2 个答案:

答案 0 :(得分:7)

嗯,我需要做的就是这个。

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

在我看来,即使在运行时分配它们,它们仍然有效。

答案 1 :(得分:0)

你的代码工作或多或少 - 你使用代码:

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

而不是

$(document).scrollTop(...)

除此之外还有效 - 请参见此处:http://jsbin.com/umatuj/2/edit