2014-09-01 2 views
0

Так что у меня проблема с функцией через .each. Это jQuery, похоже, не подбирает этот элемент через 'this'. Код ниже: (Edit: Я пытаюсь центрирование что-то, независимо от ширины экрана абсолютно для нескольких элементов)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 м :) –

0

Вы должны дать ему в качестве параметра функции centerThis() вы вызываете и заменить $ (это) в функции с именем входного параметра.

Смежные вопросы