【问题标题】:jQuery: attr for style not working in IEjQuery:样式属性在 IE 中不起作用
【发布时间】:2011-05-31 21:35:55
【问题描述】:

为什么下面的代码在 IE 浏览器(7 和 8)中不起作用?

$("ul li").each(function() {
  if(($.trim($(this).attr("style"))) != "display: none;"){
     //if content
  }else if(($.trim($(this).attr("style"))) == "display: none;"){
     //else content
  }
});

注意:前 4 个 li 元素没有“style”属性,其余 8 个有。

【问题讨论】:

  • Hack 我们可以看看与此相关的 html 吗?
  • 你可以给我们看jsfiddle.net
  • 你用的是什么版本的jquery?

标签: jquery css internet-explorer internet-explorer-8 internet-explorer-7


【解决方案1】:

不要检查style 属性。它不一定会返回当前的现实,也不会考虑其他地方定义的任何样式。

使用:hidden 过滤器,或使用css 方法:

if ($(this).is(':hidden')) {

}

// or

if ($(this).css('display') == 'none') {

}

我通常更喜欢第一种语法,因为它比display 样式考虑的更多。

【讨论】:

  • @Pack 很高兴为您提供帮助。如果答案解决了您的问题,您可以mark it as accepted
【解决方案2】:

改用此代码:

("ul li").each(function() {
  if(($.trim($(this).css("display"))) != "none"){
     //if content
  }else if(($.trim($(this).css("display"))) == "none"){
     //else content
  }
});

【讨论】:

    【解决方案3】:

    您正在将属性与属性进行比较,显示是元素属性,而不是属性。

    这样更好:

    if( ($.trim($(this).is(':visible') ) {
        // it's visible, do something
    }
    else { // no need for second condition, we *know* it's not visible!
        // it's not visible so do something else
    
    }
    

    【讨论】:

    • 如果你在一个布尔值上调用$.trim,它总是会返回一个真实的字符串。 $.trim(false)"false"
    猜你喜欢
    • 1970-01-01
    • 2010-09-29
    • 2014-06-29
    • 2013-12-13
    • 2018-02-06
    • 2023-02-06
    • 2011-03-15
    • 2015-11-21
    相关资源
    最近更新 更多