Jquery css到父元素(2级)

时间:2014-02-01 09:00:13

标签: jquery css onclick

我不知道为什么这不起作用......

jQuery(document).ready(function($){
    $('.showLink').on('click', function(){
        $(this).parents('.showContainer').css('top', '-2000px');
    });
}):

布局是:

<section id="overlay" class="showContainer">
    <div>
        <video></video>
        <div></div>
        <div id="show">
            <a href="#" class="showLink"><i class="fa fa-arrow"></i></a>
        </div>
    </div>
</section>

如果您有兴趣,可以see it live进行一些调试。

3 个答案:

答案 0 :(得分:2)

您可以在上下文中使用 .closest() ,而不是使用 .parents() ,即使两者都能胜任。

jQuery(document).ready(function($){
    $('.showLink').on('click', function(){
        $(this).closest('.showContainer').css('top', '-2000px');
    });
}): ---> remove the colon over here and replace it with ;

答案 1 :(得分:1)

使用closest(),它向上移动DOM树,直到找到所提供选择器的匹配项

jQuery(document).ready(function ($) {
    $('.showLink').on('click', function (event) {
        event.preventDefault();
        $(this).closest('.showContainer').css('top', '-2000px');
    });
});

答案 2 :(得分:1)

尝试closest仅检索与查询匹配的第一个元素,并使用event.preventDefault();来阻止<a>代码默认操作

jQuery(document).ready(function($){
    $('.showLink').on('click', function(event){
        event.preventDefault(); //use prevent Default on <a> tag.
        $(this).closest('.showContainer').css('top', '-2000px');
    });
});