scrollIntoView 在循环中第一个找到的元素
scrollIntoView first found element within 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。
你只需要确定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;
}
}
}
}
我正在试验数据-,遇到了一个我暂时无法解决的问题。
我正在尝试 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。
你只需要确定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;
}
}
}
}