假设我创建了一个这样的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?


当前回答

有一个没有JQuery的解决方案

您可以使用CSS伪类:Active在单击时隐藏元素。这个伪类主要用于锚标记和按钮。

举个例子。

A:活动{显示:无;} /*活动链接*/ <a href="#">当它被点击时将会消失

带有按钮的示例

#btn-01:active ~ p { 显示:没有; } <button id="btn-01"> click me</button> <p id="text">

其他回答

使用下面的Bootstrap 4代码片段,它扩展了jQuery:

(function( $ ) {

    $.fn.hideShow = function( action ) {

        if ( action.toUpperCase() === "SHOW") {
            // show
            if(this.hasClass("d-none"))
            {
                this.removeClass("d-none");
            }

            this.addClass("d-block");

        }

        if ( action.toUpperCase() === "HIDE" ) {
            // hide
            if(this.hasClass("d-block"))
            {
                this.removeClass("d-block");
            }

            this.addClass("d-none");
      }

          return this;
    };

}( jQuery ));

把上面的代码放到一个文件中。让我们假设"myJqExt.js" 包含jQuery之后再包含该文件。 使用语法使用它 $ () .hideShow(隐藏的); $ () .hideShow(显示);

希望对你们有帮助。: -)

Hide和hidden都已弃用并在之后被删除,在新版本中不再存在。你可以根据需要使用d-none/d-sm-none/invisible等类。 它们被删除的可能原因是隐藏/隐藏在CSS上下文中有点令人困惑。在CSS中,隐藏(hidden)用于可见性,而不是用于显示。 可见性和显示性是不同的东西。

如果你需要一个类用于可见性:hidden,那么你需要来自可见性实用程序的不可见类。

检查下面的可见性和显示实用程序:

https://getbootstrap.com/docs/4.1/utilities/visibility/

https://getbootstrap.com/docs/4.1/utilities/display/

简单:

$(function(){
  $("#my-div").removeClass('hide');
});

或者如果你想让这个类仍然在那里:

$(function(){
  $("#my-div").css('display', 'block !important');
});

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

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

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

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

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

Razz的答案很好,如果你愿意重写你所做的。

遇到了同样的麻烦,用以下方法解决了这个问题:

/** * The problem: https://github.com/twbs/bootstrap/issues/9881 * * This script enhances jQuery's methods: show and hide dynamically. * If the element was hidden by bootstrap's css class 'hide', remove it first. * Do similar in overriding the method 'hide'. */ !function($) { "use strict"; var oldShowHide = {'show': $.fn.show, 'hide': $.fn.hide}; $.fn.extend({ show: function() { this.each(function(index) { var $element = $(this); if ($element.hasClass('hide')) { $element.removeClass('hide'); } }); return oldShowHide.show.call(this); }, hide: function() { this.each(function(index) { var $element = $(this); if ($element.hasClass('show')) { $element.removeClass('show'); } }); return oldShowHide.hide.call(this); } }); }(window.jQuery);

当Bootstrap为这个问题提供修复时,将其扔掉。