Jquery 为什么插件不能处理除第一个元素之外的所有元素
我昨晚创建了图像大小调整插件。问题是如果只有一个“div.content”,我可以执行以下操作使其正常工作:Jquery 为什么插件不能处理除第一个元素之外的所有元素,jquery,Jquery,我昨晚创建了图像大小调整插件。问题是如果只有一个“div.content”,我可以执行以下操作使其正常工作: window.onload=function(){ $('div.content').image_resizer(); } 但当我再添加一些类似的“div.content”并执行以下操作时: window.onload=function(){ $.each($('div.content'),function(k,v){ $(this).
window.onload=function(){
$('div.content').image_resizer();
}
但当我再添加一些类似的“div.content”并执行以下操作时:
window.onload=function(){
$.each($('div.content'),function(k,v){
$(this).image_resizer();
});
}
插件在第一个div.content上工作,在其余的div.content上失败。你能告诉我我做错了什么吗
[编辑]
以下是标记:
<div class="content">
<img src="./images/img5.jpg" id='p1'/>
</div>
这里很好用
这表明某个地方存在标记错误
正如其他人指出的那样,没有必要迭代。您只需使用:$('div.content').image_resizer() 我不能告诉您为什么它不起作用,但是如果您想在元素上迭代,应该使用
$(选择器).each(function(){…})代码>(也在插件中)。如果您正确地编写了插件(看起来是这样),那么$('div.content')。image_resizer()
也应该适用于多个元素。请更准确地解释一下“休息失败”是什么意思。发生了什么以及您预计会发生什么?同时发布您的标记,让我们了解更多详细信息。只需两个旁注:您可以使用。每个都在一个集合上,并且您正在重置每次调用的默认值。请解释您所说的“重置默认值”是什么意思.你是在说插件代码还是这里显示的代码?你的插件不是已经为你做了迭代吗?使用$('div.content').image_resizer();是否有一个或多个div.content元素。
(function($){
$.fn.image_resizer = function(options){
$.fn.image_resizer.defaults = { MAX_HEIGHT : 280,MAX_WIDTH : 330,BORDER_WIDTH : 10 }
var opts = $.extend({},$.fn.image_resizer.defaults,options);
return this.each(function(){
//plugin code starts here
// getting array of all the images inside 'di$(this)' on which this plugin is applied
var arr = $(this).find('img');
//iterating o$(this)er the array 'arr'
$.each(arr,function(k){
//console.log(k,$(this))
// now resizing the image
img_hit=$(this).height();
img_wit=$(this).width();
//console.log(img_hit,img_wit);
//calculating image height to width ratio
var ratio = img_hit/img_wit;
if(img_wit>img_hit){
//console.log("wit module");
if(img_wit>opts.MAX_WIDTH){
//console.log("Image needs resizing");
new_wit=opts.MAX_WIDTH-(opts.BORDER_WIDTH*2);
$(this).width(new_wit);
//console.log(new_wit);
var new_hit = ratio*new_wit;
$(this).height(new_hit)
var space = opts.MAX_HEIGHT-(new_hit+(opts.BORDER_WIDTH*2));
//console.log(space);
$(this).css('margin-top',space/2);
$(this).css('margin-bottom',space/2);
}else{
//console.log("Image doesn't need resizing")
var space = opts.MAX_HEIGHT-(img_hit+(opts.BORDER_WIDTH*2));
//console.log(space);
$(this).css('margin-top',space/2);
$(this).css('margin-bottom',space/2);
}
}else{
//console.log("hit module");
if(img_hit>opts.MAX_HEIGHT){
//console.log("Image needs resizing");
new_hit = opts.MAX_HEIGHT-(opts.BORDER_WIDTH*2);
$(this).height(new_hit);
var new_wit = new_hit/ratio;
$(this).width(new_wit);
}else{
//console.log("Image doesn't need resizing");
var space = opts.MAX_HEIGHT-(img_hit+(opts.BORDER_WIDTH*2));
//console.log(space);
$(this).css('margin-top',space/2);
$(this).css('margin-bottom',space/2);
}
}
});
//plugin code ends here
});
}
})(jQuery);