假设我创建了一个这样的HTML元素,

<div id="my-div" class="hidden">Hello, TB3</div>
<div id="my-div" class="hide">Hello, TB4</div>
<div id="my-div" class="d-none">Hello, TB4</div>

如何从jQuery/Javascript显示和隐藏HTML元素。

JavaScript:

$(function(){
  $("#my-div").show();
});

结果:(与任何这些)。

我希望上面的元素被隐藏。

什么是最简单的方法隐藏元素使用Bootstrap和显示它使用jQuery?


当前回答

以如下方式初始化元素:

<div id='foo' style="display: none"></div>

然后,使用你想要显示它的事件,如下所示:

$('#foo').show();

我相信这是最简单的方法。

其他回答

此解决方案不建议使用。使用投票最多的解决方案。

hide类对于在页面加载时隐藏内容非常有用。

我的解决方案是在初始化期间,切换到jquery的隐藏:

$('.targets').hide().removeClass('hide');

然后show()和hide()应该正常工作。

最近从2.3升级到3.1时遇到了这种情况;我们的jQuery动画(slideDown)崩溃了,因为我们在页面模板的元素上放置了隐藏。我们创建了以名字间隔的Bootstrap类版本,现在它带有丑陋的重要规则。

.rb-hide { display: none; }
.rb-pull-left { float: left; }
etc...

基于上面的答案,我刚刚添加了我自己的函数,这进一步不与可用的jquery函数如.hide(), .show(), .toggle()冲突。希望能有所帮助。

    /*
     * .hideElement()
     * Hide the matched elements. 
     */
    $.fn.hideElement = function(){
        $(this).addClass('hidden');
        return this;
    };

    /*
     * .showElement()
     * Show the matched elements.
     */
    $.fn.showElement = function(){
        $(this).removeClass('hidden');
        return this;
    };

    /*
     * .toggleElement()
     * Toggle the matched elements.
     */
    $.fn.toggleElement = function(){
        $(this).toggleClass('hidden');
        return this;
    };

另一种解决这种烦恼的方法是创建自己的CSS类,在规则的末尾不设置!important,就像这样:

.hideMe {
    display: none;
}

并像这样使用:

<div id="header-mask" class="hideMe"></div>

现在jQuery隐藏工作

$('#header-mask').show();

@ dusin -graham所概述的方法也是我所做的。请记住,bootstrap 3现在使用“hidden”而不是“hide”,因为他们的文档在getbootstrap。所以我会这样做:

$(document).ready(function() {
    $('.hide').hide().removeClass('hide');
    $('.hidden').hide().removeClass('hidden');
});

那么无论何时使用jQuery的show()和hide()方法,都不会有冲突。