可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
With typical input as below...
<input type="checkbox" class="actEmail" data-value="1"/>Department one</li>
in my function...
var chksDept = $('input[type=checkbox].actEmail:checked'); var depts = Array(); chksDept.each(function() { depts.push($(this).data('value').toUpperCase()); });
Why I got the error :
$(...).data(...).toUpperCase()
is not a function?
What I need is to grab all data value in uppercase.
回答1:
The value returned from this $(this).data('value')
is of the type number
. I.e:
console.log(typeof $(this).data('value'));
You first need to check to see if it is a number
, and convert it to a string
first. Like so:
var chksDept = $('input[type=checkbox].actEmail:checked'); var depts = Array(); chksDept.each(function() { var data = $(this).data('value'); if (typeof data === 'number') { data = ""+data; } depts.push(data.toUpperCase()); }); console.log(depts);
回答2:
That's because data
method for data-value='1'
attribute returns a number and Number object doesn't have toUpperCase
method, assuming that your data-*
attributes contain both numeric and non-numeric values and you want to convert the non-numeric values to uppercase, you can use attr
method instead that returns a string.
$(this).attr('data-value').toUpperCase();
http://jsfiddle.net/B8FRE/
This happens as data-*
attributes are mapped to the dataset
property of the elements and there is a difference between properties and attributes of an element.