原生JavaScript工具使用Array.prototype.forEach
,.querySelectorAll
和.addEventListener
。
如果只有一個<a>
每<div>
Array.prototype.forEach.call(// for each
document.querySelectorAll('#container a'), // <a> in #container
function (elm, idx, arr) { // get it's info (index etc.) then
elm.addEventListener('click', function() {console.log(idx);}, false);
// make clicking it log it's index
}
);
或者有每<div>
Array.prototype.forEach.call(// for each
document.querySelectorAll('#container div'), // <div> in #container
function (elm, idx, arr) { // get it's info (index etc.) then
Array.prototype.forEach.call(// loop over each
elm.querySelectorAll('a'), // <a> in that <div>
function (a_elm, a_idx, a_arr) { // and
a_elm.addEventListener('click', function() {console.log(idx);}, false);
// make clicking it log the index of the <div>
}
);
}
);
注意很多<a>
小號登錄指數將從0
開始爲1號。
工程就像一個魅力。多謝! –