开发者

how to preform subtraction on a string

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.

开发者_如何学C

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;}
);

//


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.)


use parseInt but don't use parseInt without a radix

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.

  • The default input type for ParseInt() is decimal (base 10).
  • If the number begins in "0", it is assumed to be octal (base 8).
  • If it begins in "0x", it is assumed to be hexadecimal

why? if $(this).attr('num') would be "08" parsInt without a radix would become 0


Why dont you use jquery's data() function instead of attr() to add the num field to your tag.

  1. Jquery's data will not invalidate your markup
  2. You can add any data type in data, so there is no need to use 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.


(parseInt(imageNumber) - 1)

if the number is an integer.


parseInt() function is your friend ;)

var imageNumber = parseInt($(this).attr('num')); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜