当我点击特定的标签时,我希望它显示它的唯一值,但它一直只显示第一个值



即使点击hello ,输出也将始终是再见

如何识别特定标签并从中获取唯一值?

addEventListener('click', function(e) {
if (e.target && e.target.id == 'democlass') {
var x = document.getElementsByTagName("H1")[0].getAttribute("value");
document.getElementById("demo").innerHTML = x;
}
});
#democlass {
color: red;
}
<h1 id="democlass" value="Goodbye">Goodbye </h1>
<h1 id="democlass" value="Hello ">Hello </h1>
<p>Click the button to display the value of the id of the h1 element.</p>

<p id="demo">Here lies new text</p>

  1. ID必须是唯一的。没有两个元素可以共享相同的ID。如果你想对元素进行分组,我建议切换到类。

  2. 此外,我认为H1元素上的value属性不是有效的HTML,所以请选择文本内容。

此示例向文档添加了一个事件侦听器,但不使用类。它转而检查nodeName

const demo = document.querySelector('#demo');
document.addEventListener('click', function(e) {
const { target: { nodeName } } = e;
if (nodeName === 'H1') {
const value = e.target.textContent;
demo.textContent = value;
}
});
#democlass {
color: red;
}
<h1>Goodbye</h1>
<h1>Hello</h1>
<p>Click the button to display the value of the class attribute of the h1 element.</p>
<p id="demo">Here lies new text</p>

您可能不希望在文档级别设置事件侦听器,而只希望以标题为目标。在这个例子中,我使用了类:

const demo = document.querySelector('#demo');
const h1s = document.querySelectorAll('.democlass');
h1s.forEach(h1 => h1.addEventListener('click', handleClick, false));
function handleClick(e) {
const value = e.target.textContent;
demo.textContent = value;
}
#democlass {
color: red;
}
<h1 class="democlass">Goodbye</h1>
<h1 class="democlass">Hello</h1>
<p>Click the button to display the value of the class attribute of the h1 element.</p>
<p id="demo">Here lies new text</p>

但您可能不想在每个标题中添加一个事件侦听器。如果不是两个标题,而是100。好吧,你可以利用这样一个事实:;冒泡";DOM。CCD_ 3允许将事件侦听器添加到"的父元素;捕获";事件的泡沫化。

const demo = document.querySelector('#demo');
const container = document.querySelector('.container');
container.addEventListener('click', handleClick, false);
function handleClick(e) {
const { target: { textContent } } = e;
demo.textContent = textContent;
}
#democlass {
color: red;
}
<div class="container">
<h1 class="democlass">Goodbye</h1>
<h1 class="democlass">Hello</h1>
</div>
<p>Click the button to display the value of the class attribute of the h1 element.</p>
<p id="demo">Here lies new text</p>

  1. ID必须是唯一的-使用类
  2. 从离该窗口较近的位置委派-当您只执行addEventListener时,现在就是这样做的
  3. 使用数据属性,而不是属于表单字段的值属性。或者,使用代码中与属性相同的textContent

document.getElementById("container").addEventListener('click', function(e) {
const tgt = e.target.closest("h1"); // in case you add tags to the H1s
if (tgt && tgt.classList.contains('democlass')) {
var x = tgt.dataset.value; // or tgt.textContent
document.getElementById("demo").innerHTML = x;
}
});
#democlass {
color: red;
}
<div id="container">
<h1 class="democlass" data-value="Goodbye">Goodbye </h1>
<h1 class="democlass" data-value="Hello ">Hello </h1>
</div>
<p>Click the header to display the value of the id of the h1 element.</p>

<p id="demo">Here lies new text</p>

相关内容

最新更新