YouTube API循环问题

I am having a looping issue with my YouTube API script. The code below shows my code. The issue that I am having is that after I get a response back from the server through jquery ajax, I alert the YouTube ID of a selected specific video. For some reason, it alerts it three times. I tried modifying the code adding the ajax call outside of the loop, but it doesn't seem to work. Any help would be greatly appreciated.

Below is the app.js

function tplawesome(e,t){res=e;for(var n=0;n<t.length;n++){res=res.replace(/\{\{(.*?)\}\}/g,function(e,r){return t[n][r]})}return res}

$(function() {
    $("form").on("submit", function(e) {
       e.preventDefault();
       // prepare the request
       var request = gapi.client.youtube.search.list({
            part: "snippet",
            type: "video",
            headers: {referer: "//localhost/"},
            q: encodeURIComponent($("#search").val()).replace(/%20/g, "+"),
            maxResults: 3 // Set this to the number you want to display on the page.
       });
       // execute the request
       request.execute(function(response) {
          var results = response.result;
          $("#results").html("");
          $.each(results.items, function(index, item) {

            $.get("tpl/item.html", function(data) {


                $("#results").append(tplawesome(data, [{"title":item.snippet.title, "videoid":item.id.videoId}]));



                $('.selection').on('click', function () {

                    let url = "update_db.php";
                    let song_name2 = item.snippet.title;
                    let youtube_id = item.id.videoId;

                    $.ajax({
                        dataType: "JSON",
                        url: url,
                        type: "GET",
                        data: {song_name2: song_name2, youtube_id: youtube_id},
                        success: function (data) {

                            alert("YouTube ID: " + youtube_id );
                            //ALERTS 3 TIMES. HOW TO FIX IT???
                            /*if(data.msg === "success"){
                                console.log(data.result);
                                alert(data.result);
                            } else {
                                console.log(data.result);
                                alert(data.result);
                            }*/
                        }
                    });
                });

            });

          }); // for each loop
          resetVideoHeight();
       });
    });

    $(window).on("resize", resetVideoHeight);
});

function resetVideoHeight() {
    $(".video").css("height", $("#results").width() * 9/16);
}

function youtube_api() {
    gapi.client.setApiKey("PUBLIC KEY");
    gapi.client.load("youtube", "v3", function() {
        // yt api is ready
    });
}

Below is the item.html

<div class="item">
    <h2>Title: <strong><span style="color: red">{{title}}</span></strong></h2>
    <h2><span class="selection">I will like to perform this selection</span></h2>
    <iframe class="video w100" width="640" height="360" src="https://www.youtube.com/embed/{{videoid}}" frameborder="0" allowfullscreen></iframe>

</div>`enter code here`

Below is the index.html

<!DOCTYPE html>
<html lang="en">
    <head>      
        <title>Search your YouTube video</title>
        <meta charset="UTF-8" />                    
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Awesome videos!" />
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
        <link rel="stylesheet" href="css/style.css">
    </head>
    <body>

        <div class="row con">

            <div class="col-md-6 col-md-offset-4">
                <div style="width: 47%; height: 50px; margin-left: 22px; display: none" id="success" class="alert-success text-center"><div  style="padding-top: 15px; padding-right: 15px;"></div></div>

                <div style="width: 47%; height: 50px; margin-left: 22px; display: none" id="error" class="alert-danger text-center"><div style="padding-top: 15px; padding-right: 15px;"></div></div>

                <form>
                    <p><input type="text" id="search" placeholder="Search YouTube video" autocomplete="off" class="form-control" required /></p>
                    <p>
                        <button type="submit" id="youtube_video_search" class="form-control btn btn-primary w100">
                            <span class="glyphicon glyphicon-search"></span> Search
                        </button>
                    </p>
                </form>

            </div>
        </div>
        <div class="row">
            <div class=" col-md-6 col-md-offset-3">
                <div id="results"></div>
            </div>

        </div>

        <!-- scripts -->
        <script src="./jquery-3.3.1.js"></script>
        <script src="js/app.js"></script>
        <script src="https://apis.google.com/js/client.js?onload=youtube_api"></script>
    </body>
</html>

Not exactly sure your case, But for a workaround you can handle this with any boolean flag.

$('.selection').on('click', function () {

var isExecuted = false;

let url = "update_db.php";
let song_name2 = item.snippet.title;
let youtube_id = item.id.videoId;

$.ajax({
  dataType: "JSON",
  url: url,
  type: "GET",
  data: {song_name2: song_name2, youtube_id: youtube_id},
  success: function (data) {

       if(!isExecuted)
       {
           isExecuted = true;
           alert("YouTube ID: " + youtube_id );
           //ALERTS 3 TIMES. HOW TO FIX IT???
       }
   }
  });
});

For some reason, it alerts it three times.

You are binding click on .selection on every loop and when the loop is done, you have 3 elements with .selection, that means you bind the click on all 3 of them.

You should bind it on id or some custom tag like data-selection-id=UNIQUE_ID

item.html

Change <span class="selection"> to <span class="selection" data-selection-id="{{videoid}}">

app.js

Change $('.selection').on('click', function () { to $('.selection[data-selection-id="+ item.id.videoId +"]').on('click', function () {