jquery check the attribute element value

This question already has an answer here:

  • How do I check if an element is hidden in jQuery? 53 answers

  • The issue you have is that you're mixing jQuery and vanilla JS methods here, with .attr().display . You're also trying to compare the whole style string against (if it worked) one CSS rule.

    A better method of achieving this would be to use jQuery's is() method, along with the :visible selector. Try this:

    if ($(this).closest('li').is(':visible')) {
      // script
    }
    

    If you want only to check if the element is hidden you can check if the display is set to none using css() method. Using .attr('style') it will return the whole style on the element.

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

    Working demonstrative example (I've put the inline style just for demonstration, but I don't recommend you to use it):

    $('li').each(function(i) {
      if ($(this).css('display') == 'none') {
        console.log(i); // logs the indexes of the hidden elements
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <li style="padding-bottom: 0px; display: none;">
      <span> Content </span>
    </li>
    <li style="padding-bottom: 0px; display: none;">
      <span> Content </span>
    </li>
    <li style="padding-bottom: 0px;">
      <span> Content </span>
    </li>

    You can use :visible or :hidden selectors directly:

    if ( $('li:visible').length > 0 ) {
        // it is visible
    }
    

    You can use :visible or :hidden selectors with is():

    if ( $('li').is(':visible') ) {
        // it is visible
    }
    

    Finally, you can check the specific value of 'display' with css():

    if ( $('li').css('display') === 'none' ) {
        // it is hidden
    }
    
    链接地址: http://www.djcxy.com/p/2400.html

    上一篇: 在页面加载时获取div属性值

    下一篇: jquery检查属性元素值