jQuery for…in toUpperCase is not a function

匿名 (未验证) 提交于 2019-12-03 00:59:01

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!