Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

javascript - add click event on img with data from a json (twitch api)

the problem I have is that after creating a list with images that come from the preview of specific streams, I would like to be able to click on these images and replace the stream playing with the stream that comes from the image.

In the code below I get the streamers that play GTA V and do GTA RP. With this info, I get the nickname of the players to create the url with the preview image of their stream.

...

     function streamData(auth){
            $.ajax({
                type: 'GET',
                url: 'https://api.twitch.tv/helix/search/channels? 
                      query=FailyV&live_only=true', /** gta V id = 32982 */
                
                dataType:'json',
                headers: {
                    "Client-ID": 'id',
                    "Authorization": "Bearer "+auth
                },
                success: function(streamList) { 
                     
                    for (let i = 0; i < streamList['data'].length; i++){
                        if(streamList['data'][i]['game_id'] == 32982){
                            gtaList.push(streamList['data'][i]['display_name'])                                                                                             
                            $('#twitch-embed-low').append('<img id="thumbnail'+i+' " src="https://static-cdn.jtvnw.net/previews-ttv/live_user_'+streamList['data'][i]['display_name']+'-300x200.jpg">')
                            .on("click", function(e){
                               console.log(gtaList[i])
                            })
                            }
                        }

                        new Twitch.Embed("twitch-embed-main", {
                            width: '80%',
                            height: '80%',
                            channel: gtaList[0],
                            autoplay: false,
                            layout: "video",
                            // only needed if your site is also embedded on embed.example.com and othersite.example.com 
                            parent: ["embed.example.com", "othersite.example.com"]
                        });  
                        

                        let test = $('#twitch-embed-low')
                        console.log(test[0])
                },
                error: function(data){
                    info = document.getElementById("info")
                    info.innerHTML = "ERROR: " + data["responseJSON"]["message"] + ". Make sure your CID and corresponding secret are set in the JavaScript."
                } 
            })
        }

...

As you can see, I have tested this

...

 $('#twitch-embed-low')
 .append('<img id="thumbnail'+i+' " src="https://static-cdn.jtvnw.net/previews- 
  ttv/live_user_'+streamList['data'][i]['display_name']+'-300x200.jpg">')
 .on("click", function(e){console.log(gtaList[i])})
                            

...

but as you can imagine, it doesn't work (as I suspected) and each time I click on an image, it makes the complete loop and so it doesn't put the right stream in reading but systematically the last one and I'm not talking about the performances which are disastrous since it loads each stream 1 by 1.

So the idea is that when you click on the image, it puts the right stream in reading but I don't see how to do that.

question from:https://stackoverflow.com/questions/65645159/add-click-event-on-img-with-data-from-a-json-twitch-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's a couple of improvments you can make. The first one is you are binding the click handler to the parent element and not to the img element, meaning it will be called (n) times (the length of streamList['data']). This is because you bind the click handler multiple times to the same html element. You want to bind this event handler just to the img element.

Secondly, when the event handler is called, it will be referencing the value of i which will always be the last value of i in the loop iteration. If you want to log the value of i at the point when you create the img element, you will need to use a closure to save the state of i, for example:

var img = $('<img id="thumbnail'+i+' " src="https://static-cdn.jtvnw.net/previews- 
  ttv/live_user_'+streamList['data'][i]['display_name']+'-300x200.jpg">')
  .on("click", (function (index) {
    return function (e) {
      console.log(gtaList[index]);
    };
  })(i));

$('#twitch-embed-low').append(img)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...