1

我试图弄清楚为什么我的 CoffeeScript 代码不起作用:

HTML:

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

咖啡脚本:

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

问题是从中返回的数字attr('data-id')是一个字符串,并且将其与实际数字进行比较会导致比较失败。我应该做些什么不同的事情,以便我可以轻松地比较数字。

4

2 回答 2

6

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

id = $('a').data('id')
console.log id == 5
于 2012-10-01T17:31:59.257 回答
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

在这里运行,所有报告true

于 2012-10-01T17:28:03.260 回答