您可以使用最近的。当您需要 forEach 或正确使用地图时也不要使用地图
我还强烈建议授权(点击 div)
const containerShapes = document.getElementById("container-pock-shape")
fetch("https://pokeapi.co/api/v2/pokemon-shape")
.then(res => res.json())
.then(data => containerShapes.innerHTML = data.results
.map(({name}) => `<div class="shape-box">
<p>${name}</p>
<button>Select</button>
</div>`));
containerShapes.addEventListener("click", e => {
const tgt = e.target.closest("button")
if (tgt) console.log(tgt.closest("div.shape-box").querySelector("p").innerText)
})
#container-pock-shape {
display: flex;
flex-wrap: wrap;
}
.shape-box {
border: 2px solid red;
display: flex;
flex-direction: column;
align-items: center;
padding: 10px;
width: 200px;
}
.shape-box p {
background-color: grey;
width: 100px;
text-align: center;
font-weight: 900;
}
<body>
<div id="container-pock-shape"></div>
</body>
要获取名称,由于事件位于整个 div 上,因此您需要使用
querySelector
并找到内部 <p>
元素并获取其文本。
const containerShapes = document.getElementById("container-pock-shape")
fetch("https://pokeapi.co/api/v2/pokemon-shape")
.then(res => res.json())
.then(data => data.results.map(item =>
containerShapes.innerHTML +=
`<div class="shape-box" onclick="showName(this)">
<p>${item.name}</p>
<button>Select</button>
</div>`
))
function showName(box) {
const name = box.querySelector('p').textContent;
console.log(name);
}
#container-pock-shape {
display: flex;
flex-wrap: wrap;
}
.shape-box {
border: 2px solid red;
display: flex;
flex-direction: column;
align-items: center;
padding: 10px;
width: 200px;
}
.shape-box p {
background-color: grey;
width: 100px;
text-align: center;
font-weight: 900;
}
<body>
<div id="container-pock-shape"></div>
</body>
执行此操作的另一种方法是将单击事件仅添加到按钮,然后查找
closest
形状框,然后找到 <p>
。
const containerShapes = document.getElementById("container-pock-shape")
fetch("https://pokeapi.co/api/v2/pokemon-shape")
.then(res => res.json())
.then(data => data.results.map(item =>
containerShapes.innerHTML +=
`<div class="shape-box">
<p>${item.name}</p>
<button onclick="showName(this)">Select</button>
</div>`
))
function showName(button) {
const name = button.closest('.shape-box').querySelector('p').textContent;
console.log(name);
}
#container-pock-shape {
display: flex;
flex-wrap: wrap;
}
.shape-box {
border: 2px solid red;
display: flex;
flex-direction: column;
align-items: center;
padding: 10px;
width: 200px;
}
.shape-box p {
background-color: grey;
width: 100px;
text-align: center;
font-weight: 900;
}
<body>
<div id="container-pock-shape"></div>
</body>
嘿,我最近找到了解决此问题的简单方法(当然,如果您的文本不像按钮文本那样太长):您可以将内部文本作为元素的 id 提供。并且在事件处理程序中,您可以通过以下方式访问内部文本:这样:e.target.id希望这个解决方案可以帮助你:)