假设我创建了一个这样的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函数如.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;
    };

其他回答

使用bootstrap .collapse而不是.hidden

稍后在JQuery中,您可以使用.show()或.hide()来操作它

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

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

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

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

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

简单:

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

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

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

基于上面的答案,我刚刚添加了我自己的函数,这进一步不与可用的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;
    };

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/