将数字与数字作为字符串进行比较

时间:2012-10-01 17:25:48

标签: javascript coffeescript

我试图找出为什么我的CoffeeScript代码无效:

HTML:

<a data-id="5">Click me</a>

CoffeeScript的:

id = $('a').attr('data-id')
console.log id == 5

问题是从attr('data-id')返回的数字是一个字符串,并将其与实际数字进行比较无法进行比较。我应该做些什么,以便我可以轻松地比较数字。

2 个答案:

答案 0 :(得分:6)

您可以使用parseFloatparseInt方法,还可以查看尝试将data-属性的内容转换为适当数据类型的jQuery data方法

id = $('a').data('id')
console.log id == 5

答案 1 :(得分:0)

与Javascript相同的方法

id = '5'
console.log parseInt(id, 10) == 5 # parseInt() parses a string as an integer
console.log +id == 5              # + prefix is an "interpret as number" shorthand
console.log id == 5.toString()    # Or convert the other number to a string

Run this here, all report true