如何访问具有相同 类 的特定按钮的值

How can I access the value of a specific button that has the same classes

我正在开发一个网络应用程序,用户可以在其中搜索他们想要的歌曲歌词。我为此使用 API。现在我可以生成 10 首歌曲的结果,但问题是当用户单击“获取歌词”按钮时我无法访问该特定按钮的歌曲标题的值。如何通过单击获取歌词按钮获取特定的歌曲名称和专辑名称?这是我的最终结果:

const apiUrl = "https://api.lyrics.ovh/suggest";
const search = document.getElementById("search-btn");
const result = document.getElementById("result");
const text = document.getElementById("text");
const getLyrics = document.getElementsByClassName("get-lyrics");


//search by songs or artist...
function searchSongs(term) {
    fetch (`${apiUrl}/${term}`)
    .then (response => response.json())
    .then (data => {
        const lyricsName = document.getElementsByClassName("lyrics-name");
        for (let index = 0; index < lyricsName.length; index++) {
            const element = lyricsName[index];
            element.innerText = data.data[index].album.title;
        }

        const artist = document.getElementsByClassName("artist");
        for (let index = 0; index < artist.length; index++) {
            const element = artist[index];
            element.innerText = data.data[index].artist.name;
        }
        document.getElementById("result").style.display = "block";
        //console.log(data);
    });
}


//event listener to search song or artist
search.addEventListener("click", e => {
    //e.preventDefault();
    const searchTerm = text.value;
    if (!searchTerm) {
        alert("please type a song a name");
    } else {
        searchSongs(searchTerm);
    }
})


//event listener to get lyrics
for (let index = 0; index < getLyrics.length; index++) {
    const element = getLyrics[index];
    element.addEventListener("click", function(){
        const title = `${index + 1}`;
       
    })
}
<!doctype html>
<html lang="en">

<head>
    <title>Hard Rock Solution - Song Lyric App</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Favicon -->
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <!-- Custom css -->
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="container">
        <nav class="navbar  navbar-dark my-3">
            <a class="navbar-brand" href="#">
                <img src="images/logo.png" alt="Hard Rock Solution">
            </a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavId" aria-controls="collapsibleNavId" aria-expanded="false" aria-label="Toggle navigation">
                <img src="images/toggler-icon.svg" alt="">
            </button>
            <div class="collapse navbar-collapse" id="collapsibleNavId">
                <ul class="navbar-nav ml-auto mt-2 mt-lg-0">
                    <li class="nav-item active">
                        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Link</a>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="dropdownId" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>
                        <div class="dropdown-menu" aria-labelledby="dropdownId">
                            <a class="dropdown-item" href="#">Action 1</a>
                            <a class="dropdown-item" href="#">Action 2</a>
                        </div>
                    </li>
                </ul>
            </div>
        </nav>

        <main class="content-area">
            <div class="search-bar col-md-6 mx-auto">
                <h1 class="text-center">Lyrics Search</h1>
                <div class="search-box my-5">
                    <input id="text" type="text" class="form-control" placeholder="Enter your artist song name"> <span id="artist"></span> <span id="title"></span>
                    <button id="search-btn" class="btn btn-success search-btn">Search</button>
                </div>
            </div>

            <!-- search results -->
            <div id="result" class="search-result col-md-8 mx-auto py-4">
                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsOne" class="lyrics-name">Purple Noon</h3>
                        <p id="artistOne" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnOne" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>

                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsTwo" class="lyrics-name">Purple Noon</h3>
                        <p id="artistTwo" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnTwo" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>

                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsThree" class="lyrics-name">Purple Noon</h3>
                        <p id="artistThree" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnThree" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>

                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsFour" class="lyrics-name">Purple Noon</h3>
                        <p id="artistFour" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnFour" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>

                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsFive" class="lyrics-name">Purple Noon</h3>
                        <p id="artistFive" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnFive" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>

                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsSix" class="lyrics-name">Purple Noon</h3>
                        <p id="artistSix" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnSix" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>

                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsSeven" class="lyrics-name">Purple Noon</h3>
                        <p id="artistSeven" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnSeven" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>

                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsEight" class="lyrics-name">Purple Noon</h3>
                        <p id="artistEight" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnEight" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>

                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsNine" class="lyrics-name">Purple Noon</h3>
                        <p id="artistNine" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnNine" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>

                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsTen" class="lyrics-name">Purple Noon</h3>
                        <p id="artistTen" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnTen" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>
            </div>
            <!-- === search results === -->

            <!-- Single Lyrics -->
            <div id="lyrics" class="single-lyrics text-center">
                <button class="btn go-back">&lsaquo;</button>
                <h2 class="text-success mb-4">Pentatonix - Na Na Na</h2>
                <pre class="lyric text-white">
                    Wont go whistling like the wind blows,
                    Looking out my window,
                    Just to see the shine
                    Maybe you might call it crazy,
                    How Im acting lately,

                    Skipping through the sky



                    I see so clearly,

                    Why Im always feeling free.

                    So I sleep when my dreams,

                    Looking like reality



                    (Gonna feel it! Na na na...) x4



                    Gonna feel it!



                    I know where the greener grass grows

                    Youll just have to follow

                    To the other side



                    Lets go tiptoe on a tight rope,

                    Fallings only natural

                    Just spread your wings and fly



                    Youll see so clearly,

                    Why Im always feeling free.

                    So I sleep when our dreams

                    Looking like reality



                    (Gonna feel it! Na na na...) x4



                    Bring it down like

                    Ohh way oh

                    Yeah yeah yeah yeah yeah yeah

                    Break it down like

                    Ohh way oh

                    Yeah, yeah, yeah...

                    All around like

                    Ohh way oh

                    Yeah, yeah, yeah...

                    Sing it loud like!

                    Ohh way oh

                    Ah oo oo ooo



                    Gonna feel it! (Na na na...)

                    Make it sound like! (Na na na...)

                    All around like! (Na na na...)

                    Sing it loud like! (Na na na...)

                    Gonna feel like! (Na na na...)
                </pre>
            </div>
        </main>
    <!-- Optional JavaScript -->
    <script src="app.js"></script>
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

    <!-- Custom Script Here -->

</body>

</html>

您可以将事件对象传递给您的事件侦听器,这样您就可以知道哪个元素被点击了。在事件侦听器中,您可以检查元素的 ID 或您想要查看的属性。如果您更改按钮的 ID,您将从按钮中获取歌曲信息。

for (let index = 0; index < getLyrics.length; index++) {
    const element = getLyrics[index];
    element.addEventListener("click", function(event){
        console.log(event.target.getAttribute('id'))
        const title = `${index + 1}`;
       
    })
}

我只是将 3 个 for 循环合并为一个。

const apiUrl = "https://api.lyrics.ovh/suggest";
const search = document.getElementById("search-btn");
const result = document.getElementById("result");
const text = document.getElementById("text");
const getLyrics = document.getElementsByClassName("get-lyrics");


//search by songs or artist...
function searchSongs(term) {
    fetch (`${apiUrl}/${term}`)
    .then (response => response.json())
    .then (data => {
        const lyricsName = document.getElementsByClassName("lyrics-name");
        const getLyrics = document.getElementsByClassName("get-lyrics ");
        const artist = document.getElementsByClassName("artist");
        for (let index = 0; index < lyricsName.length; index++) {
            lyricsName[index].innerText = data.data[index].album.title;
            artist[index].innerText = data.data[index].artist.name;
          
            //event listener to get lyrics
            getLyrics[index].addEventListener("click", function(){
                    console.log("Song:"+data.data[index].album.title +" By:"+data.data[index].artist.name);
              //getLyricsAPI(title, artist);
            });
            
        }

        document.getElementById("result").style.display = "block";
        //console.log(data);
    });
}


//event listener to search song or artist
search.addEventListener("click", e => {
    //e.preventDefault();
    const searchTerm = text.value;
    if (!searchTerm) {
        alert("please type a song a name");
    } else {
        searchSongs(searchTerm);
    }
})
<!doctype html>
<html lang="en">

<head>
    <title>Hard Rock Solution - Song Lyric App</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Favicon -->
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <!-- Custom css -->
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="container">
        <nav class="navbar  navbar-dark my-3">
            <a class="navbar-brand" href="#">
                <img src="images/logo.png" alt="Hard Rock Solution">
            </a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavId" aria-controls="collapsibleNavId" aria-expanded="false" aria-label="Toggle navigation">
                <img src="images/toggler-icon.svg" alt="">
            </button>
            <div class="collapse navbar-collapse" id="collapsibleNavId">
                <ul class="navbar-nav ml-auto mt-2 mt-lg-0">
                    <li class="nav-item active">
                        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">Link</a>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="dropdownId" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>
                        <div class="dropdown-menu" aria-labelledby="dropdownId">
                            <a class="dropdown-item" href="#">Action 1</a>
                            <a class="dropdown-item" href="#">Action 2</a>
                        </div>
                    </li>
                </ul>
            </div>
        </nav>

        <main class="content-area">
            <div class="search-bar col-md-6 mx-auto">
                <h1 class="text-center">Lyrics Search</h1>
                <div class="search-box my-5">
                    <input id="text" type="text" class="form-control" placeholder="Enter your artist song name"> <span id="artist"></span> <span id="title"></span>
                    <button id="search-btn" class="btn btn-success search-btn">Search</button>
                </div>
            </div>

            <!-- search results -->
            <div id="result" class="search-result col-md-8 mx-auto py-4">
                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsOne" class="lyrics-name">Purple Noon</h3>
                        <p id="artistOne" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button  id="btnOne" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>

                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsTwo" class="lyrics-name">Purple Noon</h3>
                        <p id="artistTwo" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnTwo" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>

                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsThree" class="lyrics-name">Purple Noon</h3>
                        <p id="artistThree" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnThree" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>

                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsFour" class="lyrics-name">Purple Noon</h3>
                        <p id="artistFour" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnFour" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>

                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsFive" class="lyrics-name">Purple Noon</h3>
                        <p id="artistFive" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnFive" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>

                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsSix" class="lyrics-name">Purple Noon</h3>
                        <p id="artistSix" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnSix" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>

                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsSeven" class="lyrics-name">Purple Noon</h3>
                        <p id="artistSeven" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnSeven" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>

                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsEight" class="lyrics-name">Purple Noon</h3>
                        <p id="artistEight" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnEight" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>

                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsNine" class="lyrics-name">Purple Noon</h3>
                        <p id="artistNine" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnNine" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>

                <div class="single-result row align-items-center my-3 p-3">
                    <div class="col-md-9">
                        <h3 id="lyricsTen" class="lyrics-name">Purple Noon</h3>
                        <p id="artistTen" class="author lead">Album by <span class="artist">Washed Out</span></p>
                    </div>
                    <div class="col-md-3 text-md-right text-center">
                        <button id="btnTen" class="get-lyrics btn btn-success">Get Lyrics</button>
                    </div>
                </div>
            </div>
            <!-- === search results === -->

            <!-- Single Lyrics -->
            <div id="lyrics" class="single-lyrics text-center">
                <button class="btn go-back">&lsaquo;</button>
                <h2 class="text-success mb-4">Pentatonix - Na Na Na</h2>
                <pre class="lyric text-white">
                    Wont go whistling like the wind blows,
                    Looking out my window,
                    Just to see the shine
                    Maybe you might call it crazy,
                    How Im acting lately,

                    Skipping through the sky



                    I see so clearly,

                    Why Im always feeling free.

                    So I sleep when my dreams,

                    Looking like reality



                    (Gonna feel it! Na na na...) x4



                    Gonna feel it!



                    I know where the greener grass grows

                    Youll just have to follow

                    To the other side



                    Lets go tiptoe on a tight rope,

                    Fallings only natural

                    Just spread your wings and fly



                    Youll see so clearly,

                    Why Im always feeling free.

                    So I sleep when our dreams

                    Looking like reality



                    (Gonna feel it! Na na na...) x4



                    Bring it down like

                    Ohh way oh

                    Yeah yeah yeah yeah yeah yeah

                    Break it down like

                    Ohh way oh

                    Yeah, yeah, yeah...

                    All around like

                    Ohh way oh

                    Yeah, yeah, yeah...

                    Sing it loud like!

                    Ohh way oh

                    Ah oo oo ooo



                    Gonna feel it! (Na na na...)

                    Make it sound like! (Na na na...)

                    All around like! (Na na na...)

                    Sing it loud like! (Na na na...)

                    Gonna feel like! (Na na na...)
                </pre>
            </div>
        </main>
    <!-- Optional JavaScript -->
    <script src="app.js"></script>
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

    <!-- Custom Script Here -->

</body>

</html>