gpt4 book ai didi

javascript - 将 HTML 集合转换为 Javascript 数组?

转载 作者:行者123 更新时间:2023-12-03 06:20:57 25 4
gpt4 key购买 nike

我是一个新手,正在尝试学习w3c-dom,html-dom,刚刚经历过这个DOM-Introduction

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DOM</title>
</head>
<body>
<script type="text/javascript">
var getByTag = function(selector) {
// FIXME: Do more conditions -- Come Up with more non-verbose regex condition
return /\w/i.test(selector) ? document.getElementsByTagName(selector) : null;
}
var isHTMLCollection = function(data) {
return data.toString() === '[object HTMLCollection]';
}
var toArray = function(c) {
return Array.prototype.slice.call(c);
}
var getAllPs = getByTag('p');
console.log(isHTMLCollection(getAllPs), 'isHTMLCollection');
console.log(Array.isArray(getAllPs), 'isArray-1');
console.log(getAllPs, 'getAllPs');
var _arrayLike = toArray(getAllPs);
console.log(Array.isArray(_arrayLike), 'isArray-2');
console.log(_arrayLike.length, 'Array.length');
</script>
<p id="p1">
First Para
</p>
<p id="p2">
Second Para
</p>
</body>
</html>

在控制台上记录此内容时,当我尝试将 HTMLCollection 转换为数组时,我只得到一个空数组。

注意:也尝试使用 for 循环。

附上控制台输出,

Console-Chrome

最佳答案

是的,添加

document.addEventListener('DOMContentLoaded', function() { //rest of the code });

解决问题

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DOM</title>
</head>
<body>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
var getByTag = function(selector) {
// FIXME: Do more conditions -- Come Up with more non-verbose regex condition
return /\w/i.test(selector) ? document.getElementsByTagName(selector) : null;
}
var isHTMLCollection = function(data) {
return data.toString() === '[object HTMLCollection]';
}
var toArray = function(c) {
return Array.prototype.slice.call(c);
}
var getAllPs = getByTag('p');
console.log(isHTMLCollection(getAllPs), 'isHTMLCollection');
console.log(Array.isArray(getAllPs), 'isArray-1');
console.log(getAllPs, 'getAllPs');
var _arrayLike = toArray(getAllPs);
console.log(Array.isArray(_arrayLike), 'isArray-2');
console.log(_arrayLike.length, 'Array.length');
});
</script>
<p id="p1">
First Para
</p>
<p id="p2">
Second Para
</p>
</body>
</html>

注意:chrome 控制台的问题是,数组值是异步计算的。

<小时/>

感谢@somethinghere 和@trincot。

<小时/>

关于javascript - 将 HTML 集合转换为 Javascript 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38875659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com