2016-08-21 74 views
1

我創建函數來獲取具有相同類'視差'的某個不同div的特定高度,問題是它可以工作,但它只能獲得第一個div的高度並將其應用於其他人。我的代碼,請告訴我該怎麼做,我仍然是一個初學者。使jQuery函數單獨運行

jQuery.fn.do_para = function() { 
    var section_effect = jQuery(this); 
    var height = section_effect.height(); 
    alert(height); 
    //do something with height 
} 

if(jQuery('.page_section').hasClass('parallax')) { 
     jQuery(this).do_para(); 
} 

HTML看起來像這樣

<div class="page_section parallax" style="height:500px"></div> 
<div class="page_section"></div> 
<div class="page_section parallax" style="height:700px"></div> 

回答

1

會有問題,因爲this在jQuery插件的外部指的是jQuery對象/集合本身,而不是該集合的單個元素。因此,而不是:

jQuery.fn.do_para = function() { 
    var section_effect = jQuery(this); 
    var height = section_effect.height(); 
    alert(height); 
    //do something with height 
} 

您應該改用:

jQuery.fn.do_para = function() { 

    // if you don't want to return the collection 
    // omit the 'return' (but this will break 
    // the traditional jQuery chaining if you do): 
    return this.each(function(){ 

     // within the each() method 'this' refers 
     // to each individual element of the 
     // collection passed to the plugin: 
     var section_effect = jQuery(this); 

     var height = section_effect.height(); 
     alert(height); 
     //do something with height 
    }); 
} 

究其原因,問題指的是整個集合的是,當一個jQuery方法被用作吸附材料(使用沒有方法傳遞參數)它將引用集合中的第一個元素,並從第一個元素返回值。

如果你想要的,因爲某些原因,檢索值的數組,而不是你也可以使用:) jQuery.fn.do_para =功能({VAR = section_effect jQuery的(本);

// here we use the map() method to iterate over 
    // the collection and, from each element in the 
    // collection, return the height: 
    var height = section_effect.map(function(){ 
     $(this).height(); 

    // here we use get() to turn the jQuery map into 
    // an Array: 
    }).get(); 

    alert(height); 
    //do something with height 
} 

順便說一下,如果,該插件的代碼中,你要使用jQuery –一個別名,以節省打字,如果不出意外–那麼你就可以代替撰寫你的插件以如下方式,使用Immedately調用的函數表達:

// the argument to the function is the 
// alias with which you refer to 
// jQuery: 
(function ($) { 

    $.fn.do_para = function(){ 
    return this.each(function(){ 
     var section_effect = $(this); 
     // rest of your code.. 
    }); 
    }); 

// passing jQuery into the function: 
})(jQuery); 

參考書目: