[英]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?你如何在 jquery 中运行变量以与 php 中的 foreach 查询链接?
I have a page with a number of images which are place holders for iframes.我有一个包含许多图像的页面,这些图像是 iframe 的占位符。 When you click on the rsPlayBtn div the image is replaced with an iframe.当您单击 rsPlayBtn div 时,图像将替换为 iframe。 The only way i can think to do it to increment the id & class ($counter) and then make a jquery function for each.我能想到的唯一方法是增加 id 和类($counter),然后为每个函数创建一个 jquery 函数。 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.这似乎是一种非常低效的 i 方式,图像/iframe 的数量也是可变的,因此使用这种方法我必须创建大量不会每次都使用的变量。 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.在我看来,您正在低效地使用 class 和 id。
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. jQuery 使用“rsPlayBtn”类找到所有按钮。 You get the counter using the event.target property.您可以使用 event.target 属性获取计数器。 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.如果您想针对单个元素,也应该避免使用 class 属性。 Always use the id property for that, it is much faster.始终为此使用 id 属性,它要快得多。 This part is bad practice, see how i changed it?:这部分是不好的做法,看看我是如何改变的?:
echo "<img class='{$counter}'...";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.