【问题标题】:How to hide new elements in jQuery?如何在 jQuery 中隐藏新元素?
【发布时间】:2010-09-30 21:15:47
【问题描述】:

我有这个代码:

var $msg = jQuery('<div></div>')
    .hide()
    .appendTo(document.body)
;
if ($msg.is(":hidden")) {
    console.log("hidden");
} else {
    console.log("visible");
}

运行时,它在 Firefox 上记录 "hidden",但在 Google Chrome 上记录 "visible"。这是一个错误,还是我做错了什么?

【问题讨论】:

    标签: javascript jquery firefox dom google-chrome


    【解决方案1】:

    你有没有尝试将它附加到body后隐藏?

    $(function() {
        var $msg = jQuery('<div>hello</div>').appendTo(document.body).hide();
        if ($msg.is(":hidden")) {
            console.log("hidden");
        } else {
            console.log("visible");
        }
    }); // $()
    

    在两种浏览器上都为我工作。

    【讨论】:

      【解决方案2】:

      正如 eed3si9n 所说,.hide() 调用在 .appendTo() 调用之前。

      我想我会添加这个答案,因为我发现了另一种同样有效的方法:

      jQuery('<div></div>')
          .css("display", "none")
          .appendTo(document.body)
      ;
      

      我不确切知道它是否像这样工作,但我想将元素添加到隐藏的 DOM 应该更快,因为浏览器不需要呈现它?


      为那些像我一样必须确切知道事情是如何运作的人提供更新:

      jQuery.hide() 的代码 - 我添加的 cmets

      hide: function(speed,callback){
          return speed ?
      
              // this block of code won't be run, since speed will be undefined
              this.animate({
                  height: "hide", width: "hide", opacity: "hide"
              }, speed, callback) :
      
              // this is the relevant code
              this.filter(":visible").each(function(){
                  this.oldblock = this.oldblock || jQuery.css(this,"display");
      
                  // you can see here that it merely sets the display to 'none'
                  this.style.display = "none";
              }).end();
      }
      

      这是:hidden 选择器的代码:

      hidden: function(a) {
          return "hidden" == a.type                        // <input type="hidden" />
              || jQuery.css(a, "display") == "none"        // style.display = none
              || jQuery.css(a, "visibility") == "hidden";  // style.visibility = hidden
      }
      

      这并不能真正解释为什么 Chrome 没有将元素显示为隐藏...

      【讨论】:

      • 在脚本完成之前,浏览器不应该呈现您的更改,所以我怀疑它在速度上是否有很大差异。不过,浏览器的行为可能很奇怪,所以一切皆有可能。
      猜你喜欢
      • 2020-11-29
      • 2010-10-15
      • 1970-01-01
      • 2021-12-14
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-15
      相关资源
      最近更新 更多