我试图找出为什么我的CoffeeScript代码无效:
HTML:
<a data-id="5">Click me</a>
CoffeeScript的:
id = $('a').attr('data-id')
console.log id == 5
问题是从attr('data-id')
返回的数字是一个字符串,并将其与实际数字进行比较无法进行比较。我应该做些什么,以便我可以轻松地比较数字。
答案 0 :(得分:6)
您可以使用parseFloat或parseInt方法,还可以查看尝试将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