Jquery 如何让一个函数处理多个HTML实例?
在库页面上,我有多个“库块”实例,如下所示:Jquery 如何让一个函数处理多个HTML实例?,jquery,Jquery,在库页面上,我有多个“库块”实例,如下所示: <!-- gallery block --> <div class="gallery"> <div class="thumbnails"> <a href="images/test-image-1.jpg"><img src="images/test-image-1.jpg" alt="Test Coach"></a>
<!-- gallery block -->
<div class="gallery">
<div class="thumbnails">
<a href="images/test-image-1.jpg"><img src="images/test-image-1.jpg" alt="Test Coach"></a>
<a href="images/test-image-2.jpg"><img src="images/test-image-2.jpg" alt="Test Coach"></a>
<a href="images/test-image-3.jpg"><img src="images/test-image-3.jpg" alt="Test Coach"></a>
<a href="images/test-image-4.jpg"><img src="images/test-image-4.jpg" alt="Test Coach"></a>
<a href="images/test-image-5.png"><img src="images/test-image-5.png" alt="Test Coach"></a>
</div>
<div class="mainImage"></div>
</div>
<!-- /gallery block -->
在我的脚本文件中,我有以下内容,适用于“gallery block”的一个实例:
(function() {
'use strict';
if (jQuery('body.gallery-page').length > 0) {
jQuery('.thumbnails a').click(function(evt) {
//don't follow link
evt.preventDefault();
//get path to new image
var imgPath = jQuery(this).attr('href');
//get reference to old image
var oldImage = jQuery('.mainImage img');
//create HTML for new image
var newImage = jQuery('<img src="' + imgPath +'">');
//make new image invisible
newImage.hide();
//add to the .mainImage div
jQuery('.mainImage').prepend(newImage);
//fade in new image
newImage.fadeIn(1000);
//fade out old image and remove from DOM
oldImage.fadeOut(1000,function(){
jQuery(this).remove();
});
}); // end click
jQuery('.thumbnails a:first').click();
}
})(jQuery);
(函数(){
"严格使用",;
if(jQuery('body.gallery page')。长度>0){
jQuery('.thumbnails a')。单击(函数(evt){
//不要跟随链接
evt.preventDefault();
//获取新图像的路径
var imgPath=jQuery(this.attr('href');
//获取对旧图像的引用
var oldImage=jQuery('.mainImage img');
//为新图像创建HTML
var newImage=jQuery(“”);
//使新图像不可见
newImage.hide();
//添加到.main图像div
jQuery('.mainImage').prepend(newImage);
//淡入新图像
newImage.fadeIn(1000);
//淡出旧图像并从DOM中删除
oldImage.fadeOut(1000,函数(){
jQuery(this.remove();
});
});//结束单击
jQuery('.thumbnails a:first')。单击();
}
})(jQuery);
但是,我如何让上述内容处理大量“画廊街区”的实例呢
谢谢,您可能需要使用
不要忘记用
jQuery(this)替换jQuery('.thumbnails a')
。('.thumbnails a')
有很多可能性。前面已经提到了带有each循环的答案,但我不喜欢这个特定案例的答案
现在最简单的方法是在单击处理程序中添加以下行:
var obj = jQuery(this).closest('.gallery');
之后,要更改.mainImage
的内容,可以使用obj.find('.mainImage')
选择它
这样做,您只需对所有库使用一次单击处理程序。谢谢,但是如果
var obj=jQuery(this).closest('.gallery'),我如何定义obj
代码>在它后面?你需要在这行后面添加它:jQuery('.thumbnails a')。单击(函数(evt){
然后我是否使用obj.find('.mainImage')
像jQuery(obj.find('.mainImage')).prepend(newImage);
?不,它应该是obj.find('.mainImage').prepend(newImage);
var obj = jQuery(this).closest('.gallery');