HTML5 data-* attribute type casting strings and numbers

后端 未结 6 645
生来不讨喜
生来不讨喜 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

    Those values are simply strings to vanilla javascript; it's not attempting any conversion on its own.

    [...document.querySelectorAll("a")].forEach(a =>
        console.log("type: %s, value: %o", 
                    typeof a.dataset.value, 
                    a.dataset.value)
    );
    2.0
    2.5

    jQuery, on the other hand, tries to determine and convert to the appropriate type when accessing data attributes via data(). It's (arguably) an issue with their implementation. Their documentation (emphasis mine) actually addresses this:

    Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). A value is only converted to a number if doing so doesn't change the value's representation. For example, "1E02" and "100.000" are equivalent as numbers (numeric value 100) but converting them would alter their representation so they are left as strings. The string value "100" is converted to the number 100.

    See also HTMLElement.dataset

提交回复
热议问题