如何通过属性实时更改元素的innerHTML或innerText



我想通过setAttribute('data-content', 'value changed');实时改变.containerinnerHTML。目前,我通过.container.innerHTML = .container.getAttribute('data-content');附加innerHTML

const container = document.querySelector('.container');
container.innerHTML = container.getAttribute('data-content');
const btn = document.querySelector('.btn');
// before clicking on button
console.log(container.getAttribute('data-content'));
btn.addEventListener('click', (e) => {
container.setAttribute('data-content', 'Value Changed!!');
console.log(container.getAttribute('data-content'));
});
* {
margin: 0;
padding: 0;
outline: 0;
box-sizing: border-box;
}
body {
height: 100vh;
display: flex;
padding-top: 1rem;
align-items: flex-start;
justify-content: center;
}
.btn {
cursor: pointer;
margin-left: 1rem;
padding: 0.25rem 0.5rem;
}
<div class="container" data-content="Hello, World!"></div>
<button class="btn">Change Attribute Value</button>

就像评论里的人说的那样——你可以使用某种"JS框架"来创建这个绑定,在那里你可以定义属性和<div>标签的"HTML/text"值之间的绑定。

但是在JS/html中,你必须手动设置这个值。

const container = document.querySelector('.container');
container.innerHTML = container.getAttribute('data-content');
const btn = document.querySelector('.btn');
// before clicking on button
console.log(container.getAttribute('data-content'));
btn.addEventListener('click', (e) => {
container.setAttribute('data-content', 'Value Changed!!');
console.log(container.getAttribute('data-content'));

// Added line
container.innerHTML = container.getAttribute('data-content');
});
* {
margin: 0;
padding: 0;
outline: 0;
box-sizing: border-box;
}
body {
height: 100vh;
display: grid;
place-items: center;
}
.btn {
cursor: pointer;
padding: 0.25rem 0.5rem;
}
<div class="container" data-content="Hello, World!"></div>
<button class="btn">Change Attribute Value</button>

可以使用attrCSS中用于伪元素

的函数

const container = document.querySelector('.container');
const btn = document.querySelector('.btn');
// before clicking on button
console.log(container.getAttribute('data-content'));
btn.addEventListener('click', (e) => {
container.setAttribute('data-content', 'Value Changed!!');
console.log(container.getAttribute('data-content'));
});
* {
margin: 0;
padding: 0;
outline: 0;
box-sizing: border-box;
}
body {
height: 100vh;
display: grid;
place-items: center;
}
.btn {
cursor: pointer;
padding: 0.25rem 0.5rem;
}
.container::before{
content: attr(data-content);
}
<div class="container" data-content="Hello, World!"></div>
<button class="btn">Change Attribute Value</button>

最新更新