mercredi 22 juin 2016

Changing attr within a for loop with javascript / jquery [duplicate]

This question already has an answer here:

I have an iframe and I want to click a href and have a preselected youtube video embedded into the iframe. I can write singular functions to be called on each click, but that's redundant and seems plain bad. So I tried to put my url's into an array and then iterate through depending on which href was click, so href 0 would look at index 0 and change the video in the iframe to whatever is stored at the index in the array.

var videos = ["https://www.youtube.com/embed/yqc9zX04DXs","https://www.youtube.com/embed/kBtyCtxllP0"];
function video_manager(){
for(i = 0; i < videos.length; i++){
document.getElementById("video" + i).onclick = function() {
$("#info_frame").attr({
   "src":videos[i] 
});
   }
}
}

This is what I have been able to come up with. I imagine it's doable. I don't see why not but I'm really stuck with this Idea.

Failing that, I tried to go another route. I made these functions that work individually

function Video0() {
    $("#info_frame").attr({"src":"https://www.youtube.com/embed/yqc9zX04DXs"});
}
function Video1() {
    $("#info_frame").attr({"src":"https://www.youtube.com/embed/GOK1tKFFIQI"});
}

But if I want to have say, 8 videos I'd need 8 of them and all of my href's would call 8 different functions, which sounds so ugly to me. So i tried this...

function video_manager(){
for(i = 0; i < 2; i++){
document.getElementById("video" + i).onclick = function() {
Video+i();
   }
}
}

I'm very new to JS and JQ, any help would be appreciated XD

Aucun commentaire:

Enregistrer un commentaire