我对JS和编写jQuery插件都很陌生,所以这可能是一个非常愚蠢的问题,但我不知道如何处理。
我们说我有以下插件:
(function($){
$.fn.test = function(){
var container = $('#my-container');
var totalWidth = 0;
return container.each(function(){
// totalWidth += get the width of each element
});
};
}(jQuery));
我们假设div #my-container
拥有一些像
<div id="my-container">
<img src="wayne" width="200" />
<img src="wayne" width="300" />
<img src="wayne" width="400" />
</div>´
我现在怎样才能将容器的宽度设置为totalWidth
之后(一旦我迭代了每个元素)?我对这个jQuery链接很困惑。不是链接的原则,我应该如何继续使用每个循环中的代码?!
如果问题不清楚,请发表评论,以便我可以更准确。
最好的问候
答案 0 :(得分:3)
所以你不需要&#34;硬编码&#34; /设置容器的宽度,因为你的孩子img元素将动态定义宽度,但这个问题是迈克尔刚刚向我解释的原则之一。
首先,由于你添加test
作为jQuery函数,this
首次进入测试函数时将是你用jQuery选择的元素并调用test。 jQuery lib在调用test时设置它,因为它是一个jQuery函数扩展。 this
是容器jQuery对象。所以你需要迭代容器的子元素,每个函数中的this
将是每个img元素,用jQuery attr
获取width属性值并将每个宽度值添加到total。然后返回容器的this
以继续链接。
<script>
(function ($) {
$.fn.test = function () {
var totalWidth = 0;
this.children().each(function () {
if ($(this).attr('width')) {
totalWidth += parseInt($(this).attr('width'));
}
});
if(totalWidth > 0){
this.css('width', totalWidth);
}
return this; //keep chaining going, SinneR
};
}(jQuery));
</script>
<script>
$(function () {
$('#my-container').test().css('padding-top', '10px');//test chaining by adding more css
});
</script>
<div id="my-container">
<img src="wayne" width="200" />
<img src="wayne" width="300" />
<img src="wayne" width="400" />
</div>
答案 1 :(得分:1)
(function($){
$.fn.test = function(){
var container = $('#my-container');
var totalWidth = 0;
container.each(function(){
totalWidth += get the width of each element
});
container.css('width', totalWidth);
return container;
};
}(jQuery));
这应该有效并保持链接。