Reputation: 1881
Aside from inserting illegal attributes into an tag and invalidating my HTML, I've never done what I am trying to do before and will most likely benefit from this answer in other areas of my work.
I think the problem is I am trying to subtract "1" from a string "$(this).attr('num')"
This might work if I first convert "$(this).attr('num')" into an integer and then subtract "1" from it.
I am open to any other solutions. Thanks
//
$("#jumpPreviousButton").click(function(){
var imageNumber = $(this).attr('num');
$("#bgImageBox").css({
"background-image": "url(/galleryImages/worksImage"
+ imageNumber - 1
+".jpg)"
}).attr('num', imageNumber - 1);
return false;}
);
//
Upvotes: 1
Views: 2755
Reputation: 21864
The parseInt() function parses a string and returns an integer.
The signature is parseInt(string, radix)
so the answer to your question is:
var imageNumber = parseInt($(this).attr('num'), 10);
The second argument forces parseInt to use a base ten numbering system.
why? if $(this).attr('num') would be "08" parsInt without a radix would become 0
Upvotes: 4
Reputation: 16265
Why dont you use jquery's data()
function instead of attr()
to add the num field to your tag.
parseInt
For example: HTML:
<html>
<body>
<p>hello</p>
</body>
</html>
JS:
$('p').data('foo',52);
var val = $('p').data('foo');
alert(val);
$('p').data('foo', val + 1);
alert($('p').data('foo'));
This will alert 52
and then 53
. You can see a demo here.
Upvotes: 4
Reputation: 489
parseInt() function is your friend ;)
var imageNumber = parseInt($(this).attr('num'));
Upvotes: 3
Reputation: 116110
As you say, converting it to integer first will help. Use the parseInt()
function for that. :) (Or parseFloat()
if it is a floating point number.)
Upvotes: 5