当我单击任何按钮元素时,我很难一次获取 h1 的文本内容。有人可以帮我吗?
<div id="makeSelection" ><h1>Text Content 1</h1>
<button onclick="eveent()">Click Me</button>
</div>
<div id="makeSelection" ><h1>Text Content 2</h1>
<button onclick="eveent()">Click Me</button>
</div>
<div id="makeSelection" ><h1>Text Content 3</h1>
<button onclick="eveent()">Click Me</button>
</div>
function eveent(){
var text = document.getElementById('makeSelection').textContent;
console.log(text);
}
最佳答案
我建议制作addEventListener在 javascript 中并清除 HTML
模板中的点击事件..
然后使用 event.bind(this, item.textContent)
绑定(bind)在点击事件中监听的特定项目。
编辑:
如果您想向按钮添加事件监听器,请获取类似的按钮(假设每个 div 的类名称为 makeSelection
并且不重复相同的 id
.
const selection = document.querySelectorAll(".makeSelection button");
然后创建一个事件监听器,例如,
item.addEventListener('click', eveent.bind(this,item.previousElementSibling.textContent))
通过 item.previousElementSibling.textContent
,我们传递 h1
标签的 textContent..
const selection = document.querySelectorAll(".makeSelection button");
function eveent(clickedItem){
console.log(clickedItem)
}
selection.forEach((item,i) => {
item.addEventListener('click', eveent.bind(this,item.previousElementSibling.textContent))
})
<div class="makeSelection" >
<h1>Text Content 1</h1>
<button>Click Me</button>
</div>
<div class="makeSelection">
<h1>Text Content 2</h1>
<button>Click Me</button>
</div>
<div class="makeSelection">
<h1>Text Content 3</h1>
<button>Click Me</button>
</div>
关于javascript - 如何在javascript中一次获取一个h3的文本内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60278793/