[英]Arranging multiple outputs from forEach function into one array in javascript
I'm trying to get the hrefs
from the li
elements with javascript.我正在尝试使用hrefs
从li
元素中获取 href。 My function looks like this:我的 function 看起来像这样:
function checkUrl() {
checkUrl = function(){};
function hrefHome() {
var listCont = document.querySelectorAll(".wpcm-listings-item");
listCont.forEach(Children);
function Children(item) {
var Child = item.children;
var Hrefs = Child[0].href;
console.log(Hrefs);
}
}
}
This is returning my hrefs
like I want it to, but now I need to put all of them in localStorage
.这就像我想要的那样返回我的hrefs
,但现在我需要将它们全部放在localStorage
中。 I tried adding localStorage.vehHrefs = Hrefs;
我尝试添加localStorage.vehHrefs = Hrefs;
after the variable Hrefs, but the second one overwrites the first.在变量 Hrefs 之后,但第二个会覆盖第一个。 What I want to do is create an array of all the hrefs
and then put the array in localStorage
but I need some help.我想做的是创建一个包含所有hrefs
的数组,然后将数组放入localStorage
,但我需要一些帮助。 Below is my HTML.下面是我的 HTML。
<div class="wpcm-vehicle-results-wrapper">
<ul class="wpcm-vehicle-results">
<li class="wpcm-listings-item wpcm-listings-item-featured">
<a href="http://localhost/sr19repairables/vehicle/asdfasdf/">
<div class="wpcm-listings-item-image-wrapper">
<img src="Chevy.jpg" class="wp-post-image" onload="checkUrl()"
</div>
</a>
</li>
<li class="wpcm-listings-item wpcm-listings-item-featured">
<a href="http://localhost/sr19repairables/vehicles/repairables/2020-gmc-sierra/">
<div class="wpcm-listings-item-image-wrapper">
<img src="Chevy1.jpg" class="wp-post-image" onload="checkUrl()">
</div>
</a>
</li>
</ul>
</div>
Try:尝试:
function checkUrl() {
checkUrl = function(){};
function hrefHome() {
var listCont = document.querySelectorAll(".wpcm-listings-item");
var HrefArr = [];
listCont.forEach(Children);
localStorage.vehHrefs = JSON.stringify(HrefArr);
function Children(item) {
var Child = item.children;
var Hrefs = Child[0].href;
HrefArr.push(Href)
console.log(Hrefs);
}
}
} }
In this case, you should use map rather than forEach:在这种情况下,您应该使用 map 而不是 forEach:
function checkUrl() {
checkUrl = function () {};
function hrefHome() {
var listCont = document.querySelectorAll('.wpcm-listings-item');
var hrefs = [...listCont].map(function Children(item) {
var Child = item.children;
return Child[0].href;
});
console.log(hrefs);
// To add it to localstorage:
localStorage.setItem('key',JSON.stringify(hrefs));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.