我想为span元素设置一个值,但是当我使用querySelector()
将数据属性(data-job-value)作为目标跨度时,我得到的错误跨度未定义
let properties = ['name', 'age'];
properties.forEach(property => {
let spanElement = document.querySelector(`.prop[data-${property}]`);
spanElement.textContent = property;
});
<span class="prop" data-name></span>
答案 0 :(得分:2)
那是因为您没有匹配“ .prop [data-age]”的元素,因此if(Obj.firstname != this.state.EverContact.firstName.value)
{
this.state.CRMContact.infoIcon = 'fas fa-edit red';
}
返回querySelector
null
let properties = ['name', 'age'];
properties.forEach(property => {
let spanElement = document.querySelector(`.prop[data-${property}]`);
if (spanElement === null) {
console.log(`Error: no matching elements found for query ".prop[data-${property}]"`);
return;
}
spanElement.textContent = property;
});
如果您有如下所示的匹配元素,就不会有错误
<span class="prop" data-name></span>
let properties = ['name', 'age'];
properties.forEach(property => {
let spanElement = document.querySelector(`.prop[data-${property}]`);
if (spanElement === null) {
console.log(`Error: no matching elements found for query ".prop[data-${property}]"`);
return;
}
spanElement.textContent = property;
});