javascript - 如何将“e.target.id”用作 for 循环中的索引?
问题描述
我正在查看旧javascript
代码中的这些行:
tempIndex = window.event.srcElement.parentElement.id;
tempIndex = e.target.id;
tempindex
在 for 循环中以这种方式使用:
for(var i = tempIndex; i < all.length; i++)
Noobie 对id
标签的理解必须以字母开头
如何在 for 循环中使用它?
解决方案
如果您要正确执行此操作并希望使用 id 作为值 id 建议使用 data-attributes
https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
const elem = document.querySelector('div');
console.log(elem.id) // can be a number but cant be used in css
console.log(elem.classList[0]) // can be a number but cant use in css
// but you're right they cant be used as query selectors.
try {
console.log(document.getElementById('1'), 'but you can select with getElementById')
console.log(document.querySelector('#1')) // cant select with id
} catch (e) {
console.log('failed to select')
// "Error: Failed to execute 'querySelector' on 'Document': '#1' is not a valid selector.
}
try {
console.log(document.querySelector('.1')) // cant select with id
} catch (e) {
console.log('failed to select')
// "Error: Failed to execute 'querySelector' on 'Document': '.1' is not a valid selector.
}
.1 {
color: red;
/* this wont do anything */
}
#1 {
color: blue;
/* stil wont do nowt */
}
<div id="1" class="1">Hello, world.</div>
推荐阅读
- python - 将python文件转换为exe后找不到文件错误
- python - 澄清图像处理中的 np.unique() 值
- github - 如何在 git 存储库中“查找和替换”?
- c++ - C++:二进制到十进制,带转换过程的外观
- mysql - 从 Heroku 节点应用程序连接到远程 nysql 数据库 - 在 localhost 上工作
- java - 重现安卓的图库
- entity-framework - 如何删除孤立记录
- java - Android Studio 构建错误:发现多个文件具有操作系统独立路径“META-INF/gfprobe-provider.xml”
- python - 查找 pandas 数据框中非 NAN 元素的总数
- c# - 检查状态生存时间是否未过期