JavaScript 总是返回 true,即使事实并非如此
这可能是有史以来最奇怪的 JavaScript 问题:
$('div.GiftContainer').live('click', function () {
var self = $(this);
var price = $(this).attr('data-price');
if (!self.hasClass('selected')) {
if (price <= MyCredits) { // always returns true
alert('OK');
self.addClass('selected').siblings().removeClass('selected');
} else {
alert('MOO!');
}
} else {
self.removeClass('selected');
}
});
即使我在条件之前添加 console.log(price + ' ' + MyCredits);
也会返回 true,并且价格小于 MyCredits。
会是什么...
This is probably the weirdest JavaScript issue ever:
$('div.GiftContainer').live('click', function () {
var self = $(this);
var price = $(this).attr('data-price');
if (!self.hasClass('selected')) {
if (price <= MyCredits) { // always returns true
alert('OK');
self.addClass('selected').siblings().removeClass('selected');
} else {
alert('MOO!');
}
} else {
self.removeClass('selected');
}
});
Returns true even when I added console.log(price + ' ' + MyCredits);
right before the condition and price was smaller than MyCredits.
What could it be...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试parseInt()。这应该可以修复它,以确保它们被 JS 正确解释。
Try parseInt(). That should fix it to make sure that they're being properly interpreted by JS.
JavaScript 中有类型。这可能会令人困惑,因为它是一种动态语言。请尝试以下操作以确保两个值都是
数字
:if (parseInt(price, 10) <= parseInt(MyCredits, 10))
以下是更多信息:http://en.wikibooks.org/wiki/JavaScript/Variables_and_Types
There are types in JavaScript. This can get confusing because it is a dynamic language. Try the following to ensure both values are
numbers
:if (parseInt(price, 10) <= parseInt(MyCredits, 10))
Here is some more information: http://en.wikibooks.org/wiki/JavaScript/Variables_and_Types
那么在这种情况下
price <= MyCredits
为 true。所以没有什么问题。Well in that case
price <= MyCredits
is true. So there's nothing wrong.