我正在制作一個電影評論頁面,我使用一個按鈕來更改資格。
按下按鈕時如何獲取電影名稱?
<div class="container-movies" id="container-movies">
<div class="movie">
<span class="text1" id="title">Transformers</span>
<p class="text2">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Labore soluta ullam officiis tempore sapiente, nesciunt veniam. Vitae explicabo labore soluta quis, omnis vero nulla, dignissimos necessitatibus repellat perferendis quisquam laboriosam.
</p>
<span class="text2">gen</span>
<div class="container-cal">
<span class="cal">4</span>
<button id="cal-btn">qualify</button>
</div>
</div>
<div class="movie">
<span class="text" id="title">movie title</span>
<p class="text2">
Lorem, ipsum dolor sit amet consectetur adipisicing elit. At, sint fugit numquam dicta aperiam neque aliquam expedita ipsum sapiente assumenda rerum temporibus fuga similique sed, perspiciatis qui ipsa nihil adipisci.
</p>
<span class="text2">gen</span>
<div class="container-cal">
<span class="cal">4</span>
<button id="cal-btn">qualify</button>
</div>
</div>
這只會向我發送第一個節點的名稱:
let cal = document.getElementById("cal-btn");
cal.addEventListener('click', getcal);
uj5u.com熱心網友回復:
您可以獲取 id="title" 的內容并在 getcal 函式中使用它
const movieTitle = document.getElementById("title").innerText
uj5u.com熱心網友回復:
document.getElementById("cal-btn");
只會回傳一個元素,因為 id 是唯一的,您應該改用一個類。
對于每個按鈕,在單擊時添加一個偵聽器。然后由于結構,搜索最近的父電影以找到里面的標題。
for (let btn of document.getElementsByClassName("cal-btn")) {
btn.addEventListener("click", () => {
console.log(btn.closest(".movie").querySelector(".title").textContent)
})
}
<div class="movie">
<span class="title">Transformers</span>
<button class="cal-btn">vote</button>
</div>
<div class="movie">
<span class="title">Another film</span>
<button class="cal-btn">vote</button>
</div>
uj5u.com熱心網友回復:
您不能一遍又一遍地使用相同的 id,在這種情況下,您應該使用類或自定義屬性選擇所有按鈕并遍歷它們并呼叫您的函式
let calBtns = document.querySelectorAll(".cal-btn");
calBtns.forEach(btn => {
btn.addEventListener('click', ()=>{
alert(btn.closest('.movie').querySelector('.title').innerText)
});
})
<div class="container-movies" id="container-movies">
<div class="movie">
<span class="text1 title">Transformers</span>
<p class="text2">Lorem ipsum</p>
<span class="text2">gen</span>
<div class="container-cal">
<span class="cal">4</span>
<button class="cal-btn">qualify</button>
</div>
</div>
<hr>
<div class="movie">
<span class="text title">movie title</span>
<p class="text2">Lorem, ipsum</p>
<span class="text2">gen</span>
<div class="container-cal">
<span class="cal">4</span>
<button class="cal-btn">qualify</button>
</div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/504308.html
標籤:javascript css 用户界面 按钮