2014-09-01 58 views
0

所以我遇到了一個問題,通過.each運行一個函數,它似乎並沒有通過'this'拾取有問題的元素。下面的代碼:(編輯:我試圖絕對中心的東西,無論屏幕寬度的多個元素)jQuery問題:通過每個元素運行函數並獲取元素

$(document).ready(function(){ 
    $('.main-feature h1').each(function() { 
     centerThis(); 
    }); 
    $('.meta-feature h2').each(function() { 
     centerThis(); 
    }); 
});//doc-rdy 
function centerThis(){ 
    var trackHeight = $(this).height()/2; 
    var trackWidth = $(this).width()/2; 
    var pxInEmsHeight = Math.floor((trackHeight/146) * 100)/100; 
    var pxInEmsWidth = Math.floor((trackWidth/146) * 100)/100; 
    $(this).css({ 
     "margin-left": -pxInEmsWidth+'em', 
     "margin-top": -pxInEmsHeight+'em' 
    }); 
    $(window).resize(function(){ 
     var trackHeight = $(this).height()/2; 
     var trackWidth = $(this).width()/2; 
     var pxInEmsHeight = Math.floor((trackHeight/146) * 100)/100; 
     var pxInEmsWidth = Math.floor((trackWidth/146) * 100)/100; 
     $(this).css({ 
      "margin-left": -pxInEmsWidth+'em', 
      "margin-top": -pxInEmsHeight+'em' 
     }); 
    }); 
}//centerThis 

回答

2

你應該通過this作爲參數傳遞給centerThis功能:

$(document).ready(function(){ 
    $('.main-feature h1').each(function() { 
     centerThis(this); 
    }); 
    $('.meta-feature h2').each(function() { 
     centerThis(this); 
    }); 
});//doc-rdy 
function centerThis(elem){ 
    var trackHeight = $(elem).height()/2; 
    var trackWidth = $(elem).width()/2; 
    var pxInEmsHeight = Math.floor((trackHeight/146) * 100)/100; 
    var pxInEmsWidth = Math.floor((trackWidth/146) * 100)/100; 
    $(elem).css({ 
     "margin-left": -pxInEmsWidth+'em', 
     "margin-top": -pxInEmsHeight+'em' 
    }); 
    $(window).resize(function(){ 
     var trackHeight = $(this).height()/2; 
     var trackWidth = $(this).width()/2; 
     var pxInEmsHeight = Math.floor((trackHeight/146) * 100)/100; 
     var pxInEmsWidth = Math.floor((trackWidth/146) * 100)/100; 
     $(this).css({ 
      "margin-left": -pxInEmsWidth+'em', 
      "margin-top": -pxInEmsHeight+'em' 
     }); 
    }); 
}//centerThis 
+0

感謝Barmar,一桿進洞!生病了8米的投票:) – 2014-09-01 15:49:31

0

你必須給它作爲參數傳遞給函數centerThis()您呼叫並替換$ (this)與輸入參數的名稱一起使用。