简体   繁体   中英

How could I combine Javascript functions created by a loop in the code behind in to one function so I don't have to repeat?

How do you run through variables in jquery to link with a foreach query in php?

I have a page with a number of images which are place holders for iframes. When you click on the rsPlayBtn div the image is replaced with an iframe. The only way i can think to do it to increment the id & class ($counter) and then make a jquery function for each. This seems like a very inefficient way of doing i, also the number of images/iframes will be variable so with this method I have to create a load of variables that will not be used every time. How could I combine what I have done in to one function so I don't have to repeat?

echo "<div class='rsBtnCenterer' id='{$counter}'><div class='rsPlayBtn'>.";
echo "<img class='{$counter}'..."; 

--------

$('#1').click(function(){
var video = '<iframe src="'+ $('.1').attr('data-video') +'"></iframe>';
$('#1').hide();
$('.1').replaceWith(video);
});

$('#4').click(function(){
var video = '<iframe src="'+ $('.4').attr('data-video') +'"></iframe>';
$('#4').hide();
$('.4').replaceWith(video);
});

It's not really clear to me what your problem is. I'm assuming the last is what your question is about:

How could I combine what I have done in to one function so I don't have to repeat?

It seems to me you are using class and id inefficiently.

echo "<div class='rsPlayBtn' id='{$counter}_btn'>";
echo "<img id='{$counter}_img'..."; 


$('.rsPlayBtn').click(function(event){
  var counter = event.target.id.substring(0,1);
  var video = '<iframe src="'+ $("#" + counter + "_img").attr('data-video') +'"></iframe>';
  $("#" + counter + "_btn").hide();
  $("#" + counter + "_img").replaceWith(video);
});

Like this you don't need to create separate functions for every button. All buttons are found by jQuery using the "rsPlayBtn" class. You get the counter using the event.target property. the rest is the same code as you have, with the inserted counter.

Also you should avoid using the class property if you want to target a single element. Always use the id property for that, it is much faster. This part is bad practice, see how i changed it?:

echo "<img class='{$counter}'..."; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM