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
jQuery check if attr = value
提问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 attr
method 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 val
method returns the value of a form element.
jQuery 的val
方法返回表单元素的值。
The
.val()
method is primarily used to get the values of form elements such asinput
,select
andtextarea
. In the case of<select multiple="multiple">
elements, the.val()
method returns an array containing each selected option; if no option is selected, it returnsnull
.
该
.val()
方法主要用于获取input
,select
和等表单元素的值textarea
。在<select multiple="multiple">
元素的情况下,该.val()
方法返回一个包含每个选定选项的数组;如果未选择任何选项,则返回null
。