如何使用Vanilla JavaScript让函数作用于页面所有目标元素(当前仅首个生效)
让代码作用于所有符合条件的元素(原生JS实现)
嗨,这问题很常见~你原来的代码用了document.querySelector(),它只会返回匹配选择器的第一个元素,所以要改成获取所有匹配元素并逐个处理就好啦。
解决方案步骤:
- 用
document.querySelectorAll()替换querySelector(),这样能拿到所有符合.datepublished > time选择器的元素集合 - 遍历这个集合,对每个元素单独执行你原来的时间转换逻辑
修改后的完整代码:
// 获取所有目标time元素 const timeElements = document.querySelectorAll('.datepublished > time'); // 遍历每个元素,逐一处理 timeElements.forEach(timeElement => { // 从当前元素获取datetime属性值,转成Date对象 const time = new Date(timeElement.getAttribute('datetime')); // 更新元素文本为相对时间 timeElement.innerText = TimeAgo.inWords(time.getTime()); });
兼容旧浏览器的备选方案(如果需要支持IE等):
如果你的项目需要兼容不支持NodeList.forEach的旧浏览器,可以用传统的for循环:
const timeElements = document.querySelectorAll('.datepublished > time'); for (let i = 0; i < timeElements.length; i++) { const timeElement = timeElements[i]; const time = new Date(timeElement.getAttribute('datetime')); timeElement.innerText = TimeAgo.inWords(time.getTime()); }
小提示:
querySelectorAll()返回的是一个NodeList(节点集合),不是数组,但现代浏览器都支持用forEach直接遍历它- 确保你的
TimeAgo库已经正确加载并初始化,不然转换相对时间的逻辑会失效哦
内容的提问来源于stack exchange,提问作者Skivas
相关产品推荐
相关产品推荐

