gpt4 book ai didi

javascript - 在 p 标签上使用事件监听器

转载 作者:行者123 更新时间:2023-11-30 19:59:23 26 4
gpt4 key购买 nike

当我点击任一 p 标签 时,我无法更改 h1 标签。我在遍历 p 标签、提取值并使用该数据值更改标题时遇到问题。到目前为止,我只收到错误 Cannot read property value of undefined

window.addEventListener('load', function() {
'use strict';

const p_array = document.getElementsByTagName("p");
const count = p_array.length;

//loop through a list of elements.
for (let i = 0; i < count; i++) {

const p = p_array[i];

p.addEventListener("click", function() {

const tag = p.getElementsByTagName('p');

document.getElementById("title").innerHTML = tag.dataset.value;

})
}
});
<h1 id="title">Title</h1>
<p data-value="One">Click to change title to One</p>
<p data-value="Two">Click to change title to Two</p>
<p data-value="Three">Click to change title to Three</p>

最佳答案

window.addEventListener('load', function() {
'use strict';

const p_array = document.getElementsByTagName("p");
const count = p_array.length;

//loop through a list of elements.
for (let i = 0; i < count; i++) {

const p = p_array[i];

p.addEventListener("click", function() {

//const tag = p.getElementsByTagName('p');

document.getElementById("title").innerHTML = p.dataset.value;

})
}
});
<h1 id="title">Title</h1>
<p data-value="One">Click to change title to One</p>
<p data-value="Two">Click to change title to Two</p>
<p data-value="Three">Click to change title to Three</p>

关于javascript - 在 p 标签上使用事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53557666/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com