使用 ClickListener 创建多个 Button 并识别单击了哪个 Button? (JavaScript)
Create multiple Buttons with ClickListener and identify what Button was clicked? (JavaScript)
以 Uno Card Game 逻辑为例,当我通过点击绘制按钮动态地在玩家手上创建卡片时,我如何才能获得玩家手上点击的卡片?
类似于:
var btn = document.createElement("BUTTON");
btn.onclick = () => {
alert(btnCounter);
}
btnCounter++;
但是这个按钮的onclick函数应该写一次然后保存。
一种选择是依靠事件冒泡。我们可以将事件侦听器添加到手的容器中,然后在单击时确保单击的元素是一个按钮。在此示例中,我将卡片的值放入按钮的数据集中,但您可以从目标上的任何位置获取信息。
const hand = document.querySelector("#hand");
hand.addEventListener("click", function(e) {
if (e.target.tagName !== "BUTTON") return;
console.log(e.target.dataset.card);
});
function drawCards(numberOfCards) {
for (let i = 0; i < numberOfCards; i++) {
const button = document.createElement("button");
const card = Math.floor(Math.random() * 10);
button.setAttribute("data-card", card);
button.innerHTML = card;
hand.appendChild(button);
}
};
drawCards(5);
<div id="hand"></div>
在创建按钮(及其 id)的上下文中,在 o'clock 函数中绑定 id...
const ids = ['1', '2', '3'];
var parent = document.getElementById('parent')
ids.map(id => {
let btn = document.createElement('button');
btn.setAttribute('id', id)
btn.innerHTML = `Button ${id}`
parent.appendChild(btn)
btn.onclick = event => {
alert(id)
}
})
<div id="parent">
</div>
以 Uno Card Game 逻辑为例,当我通过点击绘制按钮动态地在玩家手上创建卡片时,我如何才能获得玩家手上点击的卡片?
类似于:
var btn = document.createElement("BUTTON");
btn.onclick = () => {
alert(btnCounter);
}
btnCounter++;
但是这个按钮的onclick函数应该写一次然后保存。
一种选择是依靠事件冒泡。我们可以将事件侦听器添加到手的容器中,然后在单击时确保单击的元素是一个按钮。在此示例中,我将卡片的值放入按钮的数据集中,但您可以从目标上的任何位置获取信息。
const hand = document.querySelector("#hand");
hand.addEventListener("click", function(e) {
if (e.target.tagName !== "BUTTON") return;
console.log(e.target.dataset.card);
});
function drawCards(numberOfCards) {
for (let i = 0; i < numberOfCards; i++) {
const button = document.createElement("button");
const card = Math.floor(Math.random() * 10);
button.setAttribute("data-card", card);
button.innerHTML = card;
hand.appendChild(button);
}
};
drawCards(5);
<div id="hand"></div>
在创建按钮(及其 id)的上下文中,在 o'clock 函数中绑定 id...
const ids = ['1', '2', '3'];
var parent = document.getElementById('parent')
ids.map(id => {
let btn = document.createElement('button');
btn.setAttribute('id', id)
btn.innerHTML = `Button ${id}`
parent.appendChild(btn)
btn.onclick = event => {
alert(id)
}
})
<div id="parent">
</div>