开发者

jQuery: attr for style not working in IE

开发者 https://www.devze.com 2023-03-09 05:52 出处:网络
Why does the following code won\'t work in IE browsers (7 and 8)? $(\"ul li\").each(function() { if(($.trim($(this).attr(\"style\"))) != \"display: none;\"){

Why does the following code won't work in IE browsers (7 and 8)?

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

Note: The first 4 li elements do not not have "style" attribute and the remaining 8 do.


Don't check the style attribute. It won't necessarily return the current reality, and it doesn't take into account any styles defined elsewhere.

Use the :hidden filter, or use the css method:

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

}

// or

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

}

I'd generally prefer the first syntax, as it takes a little more into account than just the display style.


Use this code instead:

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


Your are comparing an attribut with a property, display is an element property, not an attribute.

Better with something like this:

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

}
0

精彩评论

暂无评论...
验证码 换一张
取 消