首页 文章

在jQuery中隐藏 Headers 元素

提问于
浏览
-1

我在网页上有3个表单部分 . 每个表单部分都有一个单独的id,其中包含输入元素 . 我在这些表单元素之外有一个div,作为每个部分的 Headers . 我编写了一个脚本来检查表单部分是否有一个由类名“.form-input”标记的输入元素 . 问题是没有找到表单输入时我的脚本会使用“.title-section”类名隐藏所有 Headers . 我只需要隐藏属于表单元素的“ Headers 部分” . 如果这个 Headers 包含在表单中会更容易,但它在外面是一个单独的div .

$(function () {
    //If there is no form inputs hide title section
    // .lenght is truthy = true or false
    if (!$(".form-input").length) {
        $(".title-section").hide();
    }
});

请参阅下面的html结构

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="title-section">
                <h3>Hide Me 1</h3>
            </div>
            <div id="form-section">
                <div class="well">
                    <input class="form-input">
                </div>
            </div>  
        </div>
    </div>
</div>

1 回答

  • 2

    它隐藏所有 .title-section 元素只是因为 $('.title-section') 选择了与该选择器匹配的所有元素,无论它后面是否有 .form-input 元素 . 因此,您需要一些代码来评估 .title-section 元素后面是否有 .form-input 元素 . 像这样的东西会起作用:

    var titlesToHide = $('.title-section').filter(function(){
        return $(this).next().find('.form-input').length === 0;
    });
    
    titlesToHide.hide();
    

    我'm using jQuery' s .filter() 方法选择所需的元素 . 在我写的代码中,它查看每个 .title-section 元素,然后检查它后面的元素是否正确 - .next() -其中有一个元素,类名为 .form-input . 如果它不是 .length === 0 -过滤器函数返回 true ,因此在最终集合中包含该 .title-section 元素 .

    JS小提琴:http://jsfiddle.net/hca1y15z/

相关问题