scrollIntoView首先在循环中找到了元素

时间:2015-01-06 14:06:38

标签: javascript for-loop

我正在试验数据,并遇到了一个我目前无法解决的问题。

我正在尝试使用scrollIntoView,例如:[0],为第一个'clients [i]':

function search() {
searchTerm = document.getElementById("searchInput").value;
clients = document.getElementsByClassName("client");

for (var i = 0; i < clients.length; i++) {
    find = clients[i].getAttribute("data-search-firstname");
    if (searchTerm === find) {
        console.log("Found: " + find);
        selClient(clients[i]);
        clients[i].scrollIntoView(); // not sure where to put [0] without an error
    }
}

}

非常感谢!

编辑:

例如,如果我有多个相同的'clients [i]',我希望第一个客户端为scrollIntoView。

1 个答案:

答案 0 :(得分:0)

您只需要确定i是否是第一个结果

function search() {
    searchTerm = document.getElementById("searchInput").value;
    clients = document.getElementsByClassName("client");

    for (var i = 0; i < clients.length; i++) {
        find = clients[i].getAttribute("data-search-firstname");
        if (searchTerm === find) {
            console.log("Found: " + find);
            selClient(clients[i]);
            if (i === 0) {
                clients[i].scrollIntoView();
            }
        }
    }

}

或者在您的情况下,您似乎只希望它滚动到循环中的第一个结果searchterm === find,所以您可能想要这样做:

function search() {
    searchTerm = document.getElementById("searchInput").value;
    clients = document.getElementsByClassName("client");

    var scrolled = false;
    for (var i = 0; i < clients.length; i++) {
        find = clients[i].getAttribute("data-search-firstname");
        if (searchTerm === find) {
            console.log("Found: " + find);
            selClient(clients[i]);
            if (!scrolled) {
                clients[i].scrollIntoView();
                scrolled = true;
            }
        }
    }

}