HTML5 data-* attribute type casting strings and numbers

后端 未结 6 610
生来不讨喜
生来不讨喜 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 16:55

    I think it's more a question about how jquery identifies numbers. If you use alert(typeof(this.getAttribute("data-value")));, it spits out that it's a string both times (which is expected). So far as I know, everything in an html attribute is considered a string, just different libraries may have default behavior that interprets them differently.

    Also, a shorthand way to get a number would be something along the lines of...

    var someNumber = +$(someElt).data("value");
    

    the + will cause type coercion if the returned value is a string, or leave it alone if it's already a number.

提交回复
热议问题