本文介绍了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:

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

10-15 02:31