我有一个具有内部I的锚列表,我希望使用.querySelectorAll()选择所有目标,例如:
const targets = document.querySelectorAll('#target-1, #target-2, …')为了准备这个查询,我使用了reduce
anchors.reduce((previous, current, index) =>
index === 0 ?
current.getAttribute('href') :
previous + ', ' + current.getAttribute('href')
)这几乎是可行的,但是有一个奇怪的问题,结果如下:
https://full-url.com/#target-1, #target-2, #target-3当我只跑:
targets[0].getAttribute('href')…它返回预期结果:
target-1你可以自己试试:
const anchors = Array.from(document.querySelectorAll('a'));
console.log(anchors[0].getAttribute('href'));
console.log(anchors.reduce((previous, current, index) => index === 0 ? current.getAttribute('href') : previous + ', ' + current.getAttribute('href')));<a href="#target-1"></a>
<a href="#target-2"></a>
<a href="#target-3"></a>
这至少发生在Chrome,Safari和火狐在macOS上。
为什么将完整的URL加到第一个元素中?
发布于 2018-09-06 10:30:26
这是因为reduce需要传递一个初始值。尝试传递空字符串:
const anchors = Array.from(document.querySelectorAll('a'));
const first = anchors[0].getAttribute('href');
const all = anchors.reduce((previous, current, index) => index === 0 ? current.getAttribute('href') : previous + ', ' + current.getAttribute('href'), "");
/* The first 'href' value. */
console.log(first);
/* All 'href' values. */
console.log(all);
/* When concatenating an <a> element with a string, a link is returned. */
console.log(anchors[0] + "");<a href="#target-1"></a>
<a href="#target-2"></a>
<a href="#target-3"></a>
如果不传递初始值,则使用数组的第一个元素。因为数组中的元素是<a>元素,所以整个URL都是加在前面的,因为当您用字符串连接一个锚元素时,锚元素将被转换为一个实际的链接(如前所述)。
发布于 2018-09-06 10:31:24
如果稍微更改代码,代码就会变得更少,而且工作起来也会更少。您不必为此使用reduce。这样,您就不会篡改初始值和累积值,只需将列表锚点转换为其中的hrefs的列表并加入该…即可。
const anchors = Array.from(document.querySelectorAll('a'));
const str = anchors.map(a => a.getAttribute('href')).join(',');
console.log(str);<a href="#target-1"></a>
<a href="#target-2"></a>
<a href="#target-3"></a>
发布于 2018-09-06 10:30:44
必须将空字符串作为初始值传递给回调函数:
let anchors = Array.from(document.querySelectorAll('a'));
anchors = anchors.reduce((previous, current, index) => index === 0 ? current.getAttribute('href') : previous + ', ' + current.getAttribute('href'),"");
console.log(anchors)<a href="#target-1"></a>
<a href="#target-2"></a>
<a href="#target-3"></a>
https://stackoverflow.com/questions/52201957
复制相似问题