javascript - jQuery 无法获得顶级父级?

标签 javascript jquery

我有这样一个简单的 html 代码:

<section class="main">
    <div class="container">
        <div class="row">
            <header class="verticalCenter">
            ...
            </header>
        </div>
    </div>
</section>

另外,我有这个 jQuery:

function verticalCenter(el) {
    el.each(function() {
        var elHeight = $(this).outerHeight(true),
            parentHeight = $(this).parent('section').outerHeight(true),
            marginTop = (parentHeight - elHeight)/2;

        $(this).css('margin-top',marginTop);
    })
}

verticalCenter($('.verticalCenter'))

问题是 - jQuery 没有看到 section.main。我做错了什么?

最佳答案

你想要.closest(),而不是.parent()

  parentHeight = $(this).closest('section').outerHeight(true),

.parent() 函数检查直接父级。向它传递一个选择器有效地意味着,“给我父级,但前提是父级匹配这个选择器;否则,给我一个空列表。”

关于javascript - jQuery 无法获得顶级父级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18932108/

相关文章:

javascript - 写作助手: What's the use of the end arguments

javascript - 我的切换 div 在崩溃时崩溃都是因为一个活跃的

javascript - 使用javascript将div标签插入页面顶部

javascript - jQuery 仅显示具有单选按钮中的多个匹配类的 div

jquery - div根据浏览器窗口大小显示

javascript - 将输入字段的值添加到 anchor /链接标签

javascript - 单击 div 1,打开新内容。单击 div 2 打开 div1 的内容

Javascript 将当前日期与时间戳进行比较

javascript - Jsplumb 使用端点以编程方式添加连接

javascript - 具有包含值的属性的 jQuery 最接近元素