簡體   English   中英

我如何使用jQuery插件中的每個函數

[英]How do I work with the each function in jQuery plugins

我對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鏈接感到很困惑。 不是鏈接的原理,而是我應該如何在每個循環之外繼續使用代碼?

如果問題不清楚,請發表評論,以便讓我更加准確。

最好的祝福

因此,您不需要“硬編碼” /設置容器的寬度,因為您的子img元素將動態定義寬度,但這是Michael剛剛向我解釋的原理之一。

首先,由於您將test添加為jQuery函數, this首次輸入測試函數時, this將是您使用jQuery選擇並調用test的元素。 jQuery庫在調用test時進行設置,因為它是jQuery函數的擴展。 this是容器jQuery對象。 因此,您需要迭代容器的子元素, this在每個函數中將是每個img元素,使用jQuery attr獲得width屬性值,並將每個width值添加到總計中。 然后回到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>
(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));

這應該起作用並保持鏈接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM