$(document).ready(function () {
var t=true;
var f=false;
var cheap;
$('.day1').on('change', function (e) {
if($(this).val() == "Saturday"){
cheap = true;
}
else{
cheap=false;
}
});
if(cheap==true){
$('.pricing1').change(function () {
var price = parseFloat($('.total').data('base-price')) || 0;
$('.pricing1').each(function (i, el) {
price += parseFloat($('option:selected', el).data('cheap'));
$('.total').val('$' + price.toFixed(2));
});
//console.log('cheap',cheap)
});
}
else{
$('.pricing').change(function () {
var price = parseFloat($('.total').data('base-price')) || 0;
$('.pricing').each(function (i, el) {
price += parseFloat($('option:selected', el).data('price'));
$('.total').val('$' + price.toFixed(2));
});
console.log('cheap',cheap)
});
}
});当选择星期六时,控制台读取返回true表示廉价。但是if部分没有执行。每次只有其他部分被执行。从逻辑上讲,如果便宜是真的,它应该执行if部分。控制台将廉价值显示为true,因此廉价值为true。这太奇怪了!
发布于 2015-04-23 06:59:06
您将在dom就绪处注册事件处理程序,此时cheap具有值false,因此if条件不会得到满足,因此只有其他部分中的更改处理程序才会被注册。
$(document).ready(function () {
var t = true;
var f = false;
var cheap;
$('.day1').on('change', function (e) {
if ($(this).val() == "Saturday") {
cheap = true;
} else {
cheap = false;
}
});
$('.pricing1').change(function () {
if (cheap == true) {
var price = parseFloat($('.total').data('base-price')) || 0;
$('.pricing1').each(function (i, el) {
price += parseFloat($('option:selected', el).data('cheap'));
$('.total').val('$' + price.toFixed(2));
});
//console.log('cheap',cheap)
} else {
var price = parseFloat($('.total').data('base-price')) || 0;
$('.pricing').each(function (i, el) {
price += parseFloat($('option:selected', el).data('price'));
$('.total').val('$' + price.toFixed(2));
});
console.log('cheap', cheap)
}
});
});您可以将代码简化为
$(document).ready(function () {
var t = true;
var f = false;
var cheap;
$('.day1').on('change', function (e) {
if ($(this).val() == "Saturday") {
cheap = true;
} else {
cheap = false;
}
});
$('.pricing1').change(function () {
var data = cheap ? 'cheap' : 'price';
var price = parseFloat($('.total').data('base-price')) || 0;
$('.pricing1').each(function (i, el) {
price += parseFloat($('option:selected', el).data(data)) || 0;
});
$('.total').val('$' + price.toFixed(2));
});
});发布于 2015-04-23 07:00:51
试着改变,
if(cheap==true){至
if(cheap === true){关于解释,请看一下this的答案:
在进行任何必要的类型转换之后,
==运算符将比较是否相等。===运算符将不执行转换,因此,如果两个值的类型不同,===将直接返回false。在这种情况下,===会更快,并且可能返回与==不同的结果。在所有其他情况下,性能将是相同的。
https://stackoverflow.com/questions/29815895
复制相似问题