javascript - jQuery 问题 : Running a function through each and picking up the element

标签 javascript jquery

所以我在通过 .each 运行函数时遇到问题,jQuery 似乎没有通过“this”获取有问题的元素。下面的代码:(编辑:我试图将某些内容居中,而不管多个元素的屏幕宽度绝对如何)

$(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

最佳答案

您应该将 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

关于javascript - jQuery 问题 : Running a function through each and picking up the element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25609218/

相关文章:

javascript - 如何更新 ng-template 中的值

javascript - 将复选框的值从本地存储插入回表单

jquery - 一个 Jquery 对话框可以打开另一个 Jquery 对话框吗?

javascript - 如何使用 jQuery 修复此切换 div?

javascript - 如何成对随机化?

javascript - 将类放在脚本标签上有好处吗?

javascript - d3.js 访问 x y 坐标

javascript - 对具有多个实例的每个单个元素的 jQuery 操作

javascript - AngularJs 的标签在 ng-repeat 中不起作用

javascript - 在 three.js 中使用 jquery