如何将“ e.target.id”用作for循环的索引?

时间:2018-12-05 14:55:20

标签: javascript css

我正在用旧的javascript代码查看这些行:

tempIndex = window.event.srcElement.parentElement.id;
tempIndex = e.target.id;

tempindex正以这种方式在for循环中使用:

for(var i = tempIndex; i < all.length; i++)

Noobie对id标签的理解必须以字母开头

如何在for循环中使用它?

2 个答案:

答案 0 :(得分:2)

如果您要正确执行此操作,并且想将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>

答案 1 :(得分:0)

如果可能,ID的值除了标识DOM元素外没有其他含义。

https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id

  

该属性的值是一个不透明的字符串:这意味着网络作者不得使用它来传达任何信息。

如果HTML是JavaScript功能的来源,那么最好使用data属性:

var element = document.querySelector('[data-iterator]');

if (element) {
  var iterator = Number(element.getAttribute('data-iterator'));
  for(var i = 0; i < iterator; i++) {
    console.log(i);
  }
}
<div id="something" data-iterator="20">
</div>

相关问题