jQuery check if element have specific attribute

后端 未结 6 672
忘了有多久
忘了有多久 2021-01-06 03:07

I am trying to see if an element have a specific CSS attribute. I am thinking at something like this:

if ( !$(this).attr(\'font-style\', \'italic\')) {
alert         


        
相关标签:
6条回答
  • 2021-01-06 03:40

    Try a morf of the conditional and a few semi columns added:

    $(document).ready(function()
    {
        $('#selectable1 span').live('click', function()
        {
            if ($(this).css('font-style') != "italic")
            {
                alert("yop");
            } 
            else
            {
                alert("nope");
            };
        });
    }); 
    

    NOTE: Making assumption regarding the select and subsequent markup based on other comments - would need to see the html to make sure on that.

    0 讨论(0)
  • 2021-01-06 03:41

    You are trying to get a css style. The css method can get the information

    if ( !$(this).css('font-style') == "italic") {
        alert ("yop")
    }
    else {
        alert ("nope")
    }
    
    0 讨论(0)
  • 2021-01-06 03:43

    you can get the font-style element and use == operator to get true/false value:

    if($(this).attr('font-style') == 'italic')
    {
        alert('yes')
    }
    else
    {
        alert('no')
    }
    
    0 讨论(0)
  • 2021-01-06 03:49

    Here's a simple plugin to do that (tested):

    $.fn.hasCss = function(prop, val) {
        return $(this).css(prop.toLowerCase()) == val.toLowerCase();
    }
    
    $(document).ready(function() {
        alert($("a").hasCss("Font-Style", "Italic"));
    });
    
    <a style="fonT-sTyle:ItAlIc">Test</a>
    
    0 讨论(0)
  • 2021-01-06 03:51

    You want this:

    if ( $(this).attr('font-style') !=  'italic') {
      alert ("yop")
    }
    else {
      alert ("nope")
    }
    
    0 讨论(0)
  • 2021-01-06 04:05

    How about this

     if ($(this).css('font-style', 'italic')) {
        alert ("yes")
        }
        else {
        alert ("nop")
        }
    

    But I'd rather use console.log instead of alert if I were you, use firebug its less annoying and more fun :D

    <script>
    
         $(document).ready(function(){ 
             $('#selectable1 span').live('click', function() { 
                if (!($(this).css("font-style","italic"))){ 
                    alert ("yop"); 
                  } else { 
                    alert ("nope"); 
                  } 
             }); 
         }); 
    
    </script> 
    

    I don't see why this shouldn't work..

    0 讨论(0)
提交回复
热议问题