Jquery divide cast as int issue
I am trying to divide two variables in Jquery as follows:
var image_width = parseInt($object.width());
var image_height = parseInt($object.height());
var image_ratio = image_width/image_height;
However, when I attempt to use image_ratio in an if statement...
if (image_ratio < 1)开发者_StackOverflow社区 //image is taller than it is wide
{
//do something...
}
And I know that the image is taller than it is wide but the function is not entering the if statement. Is this because when two int's divide it generates an int? If so, how can I get decimal values in order to check if the ratio is less than 1?
Thanks!
what is the result of alert($object.height())
? If it's possible that $object is an empty jquery collection, then.height()
will return null
, and parseInt(null)
will return NaN
, giving you NaN
for image_ratio
. Any comparison between NaN
and another value will always return false, which would explain the behavior you're seeing.
if $object.height()
is returning 0
, you'll also get NaN
for image_ratio
, and then you need to look at your jQuery selection. Are you selecting the correct element? What does $object[0].height
give you?
JavaScript doesn't have ints, only "Numbers" (double-precision floating point), so that's not the problem.
Check the actual values of each variable.
You have something else wrong because dividing two numbers will return a decimal value if they don't divide perfectly evenly. Here's a jsFiddle to see for yourself: http://jsfiddle.net/jfriend00/wnh9Q/.
var width = 4;
var height = 3;
var aspectRatio = height/width;
if (aspectRatio < 1) {
$("#if").html("Inside the if() statement."); // it goes in here
}
$("#result").html(aspectRatio); // outputs 0.75
To solve your issue, you need to look at the input values $object.width() and $object.height() and see what is wrong there.
At which point are you calling the width()
and height()
functions on the image object? If the image isn't yet loaded when the values are retreived, the values are probably wrong. In this case, try calculating the ratio in a function attached to the load event on the image.
No, the division doesn't give an integer result. The parseInt
method doesn't give an integer result either, because there is no integer data type in Javascript.
Besides, the width
and height
methods returns numbers, not strings, so there is no point to parse them. That would only convert the number into a string, and then back to a number. Just get the values:
var image_width = $object.width();
var image_height = $object.height();
There is however nothing in your code that would not work, so there has to be something outside the code that you show that doesn't work.
Some possible reasons:
$object
doesn't contain any elements.- The image is not loaded yet, so the element doesn't have any size.
If it's the latter, you should run your code in the load
event rather than in the ready
event.
精彩评论