I was trying to figure out why my CoffeeScript code was not working:
HTML:
<a data-id="5">Click me</a>
CoffeeScript:
id = $('a').attr('data-id')
console.log id == 5
The problem is the number being returned from attr('data-id')
is a string and comparing it to an actual number fails the comparison. What should I be doing differently so that I can easily compare numbers.
You may use parseFloat or parseInt methods, and also take a look at jQuery data method which tries to convert content of data-
attribute to appropriate data type
id = $('a').data('id')
console.log id == 5
Same way you do in 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.