HTML5 data-* attribute type casting strings and numbers

后端 未结 6 613
生来不讨喜
生来不讨喜 2021-01-07 16:18

Why is the value of data-value=\"2.0\" cast to a String and the value of data-value=\"2.5\" cast to a Number? I can handle this fine within my func

6条回答
  •  一向
    一向 (楼主)
    2021-01-07 17:02

    By default anything parsed from an attribute will be a string, you will need to convert it to a number if you need to use it as a number. The best way I've been able to handle this is by wrapping it with the Number function (native javascript)

    var number = Number($(this).data("value"));
    
    parseInt will return an integer (whole number), so if you want to keep your decimal values you'll need to use Number. Word of caution with parseInt, it is always better to specify the base if you want to parse an int, parseInt($(this).data("value"), 10);

提交回复
热议问题