首页 > 解决方案 > 如何将“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 循环中使用它?

标签: javascriptcss

解决方案


如果您要正确执行此操作并希望使用 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>


推荐阅读