jQuery check if attr = value

后端 未结 2 1664
半阙折子戏
半阙折子戏 2020-12-13 12:28

I seem to be having trouble with my code. I need to say:

if ( $(\'html\').attr(\'lang\').val() == \'fr-FR\' ) {
    // do this
} else {
    // do that
}


        
相关标签:
2条回答
  • 2020-12-13 13:10

    jQuery's attr method returns the value of the attribute:

    The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

    All you need is:

    $('html').attr('lang') == 'fr-FR'
    

    However, you might want to do a case-insensitive match:

    $('html').attr('lang').toLowerCase() === 'fr-fr'
    

    jQuery's val method returns the value of a form element.

    The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option; if no option is selected, it returns null.

    0 讨论(0)
  • 2020-12-13 13:19

    Just remove the .val(). Like:

    if ( $('html').attr('lang') == 'fr-FR' ) {
        // do this
    } else {
        // do that
    }
    
    0 讨论(0)
提交回复
热议问题