如何解决如何使用纯 javascript 遍历每个 div 标签?
""
但是控制台会记录如下内容:0 1 2 3 4...
我希望每次按回车键时都记录每个新索引。所以它会像:0(输入)1(输入)2(输入)3...
我该怎么做?
解决方法
您可以创建一个处理函数来设置 index
变量,并缓存 div
,然后返回一个新函数(称为 closure),每当事件发生。
function handler() {
// Create the index and divs variable.
// These variables will be carried into the closure
let index = 0;
const divs = document.querySelectorAll('div');
// Because the closure maintains references
// to the variables in its "outer lexical environment"
// you can update them when it's returned from the handler
return function () {
// Now just check to see if the index value is
// less than the length of the collection of elements
// If it is log the value,and increase the index
if (index < divs.length) {
console.log(index);
index++;
} else {
console.log('Nothing to log');
}
}
}
const keywords = document.querySelector('#keywords')
// Call the handler function so that the the variables
// can be initiated,and the closure that the listener will be
// using can be returned
keywords.addEventListener('keyup',handler(),false);
<input type="text" id="keywords"></input>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
window.onload = () => {
let keyword = document.getElementById('keywords');
var enterCount = 0;
var divs = document.getElementsByTagName('span');
keyword.addEventListener('keyup',function(e) {
if (e.key === 'Enter') {
if (enterCount < divs.length) {
console.log(enterCount);
enterCount += 1;
}
}
})
}
<input type="text" id="keywords"></input>
<span>123</span>
<span>345</span>
<span>567</span>
我认为您正在寻找这样的东西。您可以将 span 标签更改为您的 div。此 span 标记仅用于示例目的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。