jQuery 检查是否 attr = 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11211222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:20:25  来源:igfitidea点击:

jQuery check if attr = value

jqueryconditionalattrif-statement

提问by beefchimi

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
}

When I check the console, I just get an error telling me this isn't a function. Help would be appreciated.

当我检查控制台时,我收到一条错误消息,告诉我这不是一个函数。帮助将不胜感激。

Thanks,

谢谢,

回答by Miguel Ribeiro

Just remove the .val(). Like:

只需删除 .val()。喜欢:

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

回答by zzzzBov

jQuery's attrmethod returns the value of the attribute:

jQuery 的attr方法返回属性的值:

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.

.attr()方法仅获取匹配集中第一个元素的属性值。要单独获取每个元素的值,请使用循环构造,例如 jQuery.each().map()方法。

All you need is:

所有你需要的是:

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

However, you mightwant to do a case-insensitive match:

但是,您可能希望进行不区分大小写的匹配:

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


jQuery's valmethod returns the value of a form element.

jQuery 的val方法返回表单元素的值。

The .val()method is primarily used to get the values of form elements such as input, selectand 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.

.val()方法主要用于获取input,select和等表单元素的值textarea。在<select multiple="multiple">元素的情况下,该.val()方法返回一个包含每个选定选项的数组;如果未选择任何选项,则返回null