HTML5 data- *属性类型转换字符串和数字 [英] HTML5 data-* attribute type casting strings and numbers

查看:1667
本文介绍了HTML5 data- *属性类型转换字符串和数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么的值= data-value =2.0强制转换为String且值 data-value =2.5强制转换为数字?
我可以在我的功能中处理这个问题。我只是想了解一下Javascript如何处理数字和字符串。这种让我措手不及。

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 function. I'm just trying to understand a little more about how Javascript handles Numbers and Strings. This kind of caught me off guard.

<a data-value="2.0">2.0</a>
<a data-value="2.5">2.5</a>





$("a").click(function() {
    alert(typeof $(this).data( "value"));   
});

[摆弄它]

推荐答案

这些值只是字母串到vanilla javascript;它不会自行尝试任何转换。

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)
);

<a data-value="2.0">2.0</a>
<a data-value="2.5">2.5</a>

另一方面,jQuery在通过 数据() 。它(可以说)是他们实施的一个问题。他们的文档(强调我的)实际上解决了这个问题:

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:


每次尝试都将字符串转换为JavaScript值(包括布尔值,数字,对象,数组和null)。如果这样做不会更改值的表示,则只将值转换为数字。 例如,1E02和100.000等同于数字(数值100),但转换它们会改变它们的表示形式,因此它们将保留为字符串。字符串值100将转换为数字100。

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.

另请参阅 HTMLElement。数据集

这篇关于HTML5 data- *属性类型转换字符串和数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆