我如何用相同的数据填充页面(具有相同类的几个元素?

问题描述 投票:-2回答:3

我知道如何显示当前年份并通过ID传递它,但是该ID当然只会显示一次。我需要能够在整个站点中多次显示它。

我该如何完成?

//get year 
var yyyy = new Date().getFullYear();

currYear.innerHTML = yyyy;


//trying to display as a class
document.getElementsByClassName('thisYear')[0] = yyyy;
<span id="currYear"></span>
<span class="thisYear"><span>
javascript getelementbyid getelementsbyclassname
3个回答
3
投票

据我了解,您正在尝试将当前年份添加到HTML中的多个元素?当前,您仅将其分配给第一个([0])。您可以使用类thisYear解析每个元素,然后将当前年份添加到它们。

//get year 
var yyyy = new Date().getFullYear();

//trying to display as a class
//the document.getElementByClassName returns a htmlCollection. not an array directly.
//https://stackoverflow.com/a/3871602/5784924
Array.from(document.getElementsByClassName('thisYear')).forEach(function(element) {
  element.innerHTML = yyyy;
});
<div class="thisYear">this year</div><br>
<div class="thisYear">this year</div><br>
<div class="notThisYear"> not this year</div><br>
<div class="notThisYear">not this year</div><br>
<div class="thisYear"></div>

P.S。此答案仅反映OP的要求。如果您希望看到更多与浏览器兼容的最新信息,请参阅Scott Marcus' answer


2
投票

[document.getElementsByClassName('thisYear')[0] = yyyy;尝试将调用返回的DOM元素设置为年份,而不是将DOM元素的某些属性设置为Year。

为了使您的代码正常工作,“快速修复”是将.innerHTML添加到您的行中:

document.getElementsByClassName('thisYear')[0].innerHTML = yyyy;

但是,.getElementsByClassName()(以及来自1990年代,例如getElementsByTagName()getElementsByName()和其他)。我已经写过这个和这个主意向返回节点列表的方法的末尾添加索引的过程here

相反,使用现代的,符合标准的.querySelector().querySelectorAll(),然后您需要遍历集合并分别修改元素。

请参见其他注释:

//get year 
var yyyy = new Date().getFullYear();


// .querySelectorAll returns a node list, which is not an actual Array implementation.
// IE doesn't support calling .forEach on node lists, so if you need to support IE
// you'll need to convert the node list into an aray in order to call .forEach and you'll
// need to do it in a way that IE understands (not Array.from()):

// Array.prototype.slice.call(document.querySelectorAll('.thisYear')).forEach(function(element) {

// But, if you are not concerned with IE, you can call .forEach() directly on the node list
document.querySelectorAll('.thisYear').forEach(function(element) {
  // When the content you wish to update doesn't contain any HTML, don't use .innerHTML
  // which has performance and potential security implications, use .textContent instead
  element.textContent = yyyy;
});
div { margin-bottom:1em; }
<div class="thisYear">this year</div>
<div class="thisYear">this year</div>
<div class="notThisYear"> not this year</div>
<div class="notThisYear">not this year</div>
<div class="thisYear"></div>

0
投票

我想您正在尝试将当前日期分配给具有相同类的多个元素。请在下面查看此示例。

var items = document.getElementById( 'items' ),
    divs = document.getElementsByClassName( 'count' );

[].slice.call( divs ).forEach(function ( div ) {
    div.innerHTML = items.innerHTML;
});

来源:Replace innerHTML of all divs with same class

© www.soinside.com 2019 - 2024. All rights reserved.