【问题标题】:Scroll to a particular element in a UL list with dynamic ids滚动到具有动态 ID 的 UL 列表中的特定元素
【发布时间】: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


    【解决方案1】:

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

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

    在我看来,即使它们是在运行时分配的,这些 id 仍然有效。

    【讨论】:

    • 请尝试包含跨浏览器的方式。 :-)
    • 我做了一个console.log(document.getElementById(id)) ,看到有一个方法scrollIntoView()..用它和viola,它起作用了!
    【解决方案2】:

    您的代码或多或少地工作 - 但是您正在使用代码:

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

    而不是

    $(document).scrollTop(...)
    

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

    【讨论】:

    • 哦,在我的iOS模拟器上不行。。我刚刚试了一下
    • 嗯,iOS 处理此代码的方式可能有些问题(因为它可以在常规浏览器 (Chrome) 中运行)。无论如何,您已经发布了适合您的解决方案,所以很好。
    猜你喜欢
    • 2012-10-03
    • 1970-01-01
    • 2015-09-06
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 2022-12-18
    • 2019-07-13
    相关资源
    最近更新 更多