在javascript中将某个类的所有元素的ID放入数组
我读了,被接受的答案是:在javascript中将某个类的所有元素的ID放入数组,javascript,Javascript,我读了,被接受的答案是: var ids = $('.cookie').map(function(index) { // this callback function will be called once for each matching element return this.id; }); 如何在纯javascript中完成上述操作?我建议如下: // using Function.prototype.call() to apply // Array.prototy
var ids = $('.cookie').map(function(index) {
// this callback function will be called once for each matching element
return this.id;
});
如何在纯javascript中完成上述操作?我建议如下:
// using Function.prototype.call() to apply
// Array.prototype.map() to the array-like NodeList returned
// by document.querySelectorAll():
var elementIDs = Array.prototype.map.call(document.querySelectorAll('.cookie'), function (cookie) {
// the first argument to the anonymous function ('cookie') is
// the array element of the array over which we're iterating,
// and is here a DOM node.
// here, we return the id property of the current node:
return cookie.id;
});
参考资料:
- 我建议如下:
// using Function.prototype.call() to apply
// Array.prototype.map() to the array-like NodeList returned
// by document.querySelectorAll():
var elementIDs = Array.prototype.map.call(document.querySelectorAll('.cookie'), function (cookie) {
// the first argument to the anonymous function ('cookie') is
// the array element of the array over which we're iterating,
// and is here a DOM node.
// here, we return the id property of the current node:
return cookie.id;
});
参考资料: