jQuery 如何从另一个变量中减去一个变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19551427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I subtract one variable from another?
提问by Daniel
I have this piece of jquery code:
我有这段jquery代码:
jQuery(document).ready(function($) {
var totaalBreedte = $("#menuus").width();
var menuBreedte = $("#eersteMenu").width();
var over = totaalBreedte - menuBreedte;
alert(over);
});
For example, when totaalBreedte = 800 and menuBreedte = 400. I can sum the two values, which alerts 1200, but when i substract them like above I recieve 0. I tried to cast them as a number and tried parseInt() but this doesn't make any difference. Someone who knows what i'm missing here?
例如,当 totalBreedte = 800 和 menuBreedte = 400 时。我可以将两个值相加,这会发出 1200 的警报,但是当我像上面一样减去它们时,我收到 0。我尝试将它们转换为数字并尝试使用 parseInt() 但这并没有没有任何区别。有人知道我在这里想念什么吗?
回答by Afzaal Ahmad Zeeshan
your code is working perfectly. I have just changed the element selectors for width to a simple int. And it worked correctly. Here is the fiddle:
您的代码运行良好。我刚刚将宽度的元素选择器更改为简单的 int。它工作正常。这是小提琴:
http://jsfiddle.net/afzaal_ahmad_zeeshan/KnbEh/
http://jsfiddle.net/afzaal_ahmad_zeeshan/KnbEh/
And here is a snapshot;
这是一个快照;
You can see the value of the result being sent to alert. What you should do is to check the values for them. As @Vega has already mentioned, it looks like they are both 600
which is why, their sum is 1200, and when you subtract, its a 0. You might want to recheck the values.
您可以看到发送到警报的结果的值。您应该做的是检查它们的值。正如@Vega 已经提到的,看起来它们都是,600
这就是为什么,它们的总和是 1200,当你减去时,它是 0。你可能想重新检查这些值。
回答by franzbischoff
Did you tried to look into the actual value of both totaalBreedte and menuBreedte? Tried another browser? You can use for example the Chrome's console to try some JavaScript lines and debug this. Your code seems ok.
您是否尝试研究过 totalBreedte 和 menuBreedte 的实际价值?尝试其他浏览器?例如,您可以使用 Chrome 的控制台来尝试一些 JavaScript 代码行并进行调试。你的代码看起来没问题。