2014-09-01 59 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)与输入参数的名称一起使用。