【问题标题】:NaN Issue - Unable to display number in JqueryNaN 问题 - 无法在 Jquery 中显示数字
【发布时间】:2018-06-15 10:27:46
【问题描述】:

大家新年快乐! 所以我正在构建一个卡路里计算器,但我遇到了一个小问题。

我基本上有 4 个变量要总结和展示:

  1. 总卡路里#total
  2. 碳水化合物
  3. 脂肪
  4. 蛋白质

我在 2/3/4 成功,但是,我收到 1 的错误。不知道为什么。 只有计算器的“主菜”部分有效,所以请点击它,然后“基地”会滚下来。从那里选择一个菜单项后,您就会看到问题。

另外,这不是必须的,但我会很感激,当您将鼠标悬停在中间的图像上时,我想在菜单项上放置一个 + 符号覆盖。我似乎无法正确使用 CSS。如果任何退伍军人有一个想法,将不胜感激。 (我一直在玩 position 和 top 属性,但我没弄好)

代码如下:

<!DOCTYPE html>
<html>

<head>
  <title>Padthai calc</title>
  <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>

<body>


  <div class="content">
    <h1>PADTHAI CALORIE CALCULATOR</h1>
    <h2>Select a meal to begin your calculation</h2>


  <ul id="menuitems">
    <li><button id="maindish"><img src='http://www.padthai.decorolux.com/wp-content/uploads/2017/11/hangulat01.jpg'><span class="bigtext">Main Dish</span></button></li>
    <li><button id="soups"><img src='http://www.padthai.decorolux.com/wp-content/uploads/2017/11/hangulat01.jpg'><span class="bigtext">Soup</span></button></li>
    <li><button id="teas"><img src='http://www.padthai.decorolux.com/wp-content/uploads/2017/11/oktoberhat05.jpg'><span class="bigtext">Teas</span></button></li>
    <li><button id="desserts"><img src='http://www.padthai.decorolux.com/wp-content/uploads/2017/11/IMG_5968-6.jpg'><span class="bigtext">Desserts</span></button></li>
  </ul>

  <div>


  </div>

  <div id="contenttable">
    <div class="maindish">
      <h1>Main Dish</h1>
      <hr>

      <table>
          <th>Bases</th>

          <td><button class="base ingredient container" data-calories="517.2" data-carbs="76.1" data-fat="14.4" data-proteins="20.8" vegetarian glutenfree weightloss lactosefree vegan><img class="image" src='http://www.padthai.decorolux.com/wp-content/uploads/2017/11/hangulat01.jpg'><span style="smalltext">Rice Noodle</span></button></td>

          <td><button class="base ingredient container" ata-calories="510.5" data-carbs="66.1" data-fat="14.1" data-proteins="29.8" vegetarian lactosefree><img class="image" src='http://www.padthai.decorolux.com/wp-content/uploads/2017/11/hangulat01.jpg'>Egg Noodle</button></td>

          <td><button class="base ingredient container" data-calories="506.9" data-carbs="76.9" data-fat="14.1" data-proteins="18.1" vegetarian lactosefree vegan><img  class="image"src='http://www.padthai.decorolux.com/wp-content/uploads/2017/11/hangulat01.jpg'>Vermicelli</button></td>

          <td><button class="base ingredient container" data-calories="476.6" data-carbs="53.8" data-fat="16.6" data-proteins="28" vegetarian lactosefree vegan><img  class="image" src='http://www.padthai.decorolux.com/wp-content/uploads/2017/11/hangulat01.jpg'>Whole Grain Noodle</button></td>

          <td><button class="base ingredient container" data-calories="514.8" data-carbs="72.4" data-fat="14.8" data-proteins="23" vegetarian><img class="image" src='http://www.padthai.decorolux.com/wp-content/uploads/2017/11/hangulat01.jpg'>White Rice</button></td>

          <td><button class="base ingredient container" data-calories="516" data-carbs="70.1" data-fat="16" data-proteins="22.9" glutenfree vegetarian><img class="image" src='http://www.padthai.decorolux.com/wp-content/uploads/2017/11/hangulat01.jpg'>Brown Rice</button></td>

          <td><button class="base ingredient container" data-calories="106.6" data-carbs="14.2" data-fat="1.8" data-proteins="8.4" glutenfree vegetarian lactosefree vegan><img class="image" src='http://www.padthai.decorolux.com/wp-content/uploads/2017/11/hangulat01.jpg'>Vegetable Base</button></td>

      </table>
    </div>



<div class="soups">
    <h1>Soups</h1>
<hr>
      <table>
        <tr>
          <th>Company</th>
          <th>Contact</th>
          <th>Country</th>
        </tr>
        <tr>
          <td>Alfreds Futterkiste</td>
          <td>Maria Anders</td>
          <td>Germany</td>
        </tr>
        <tr>
          <td>Centro comercial Moctezuma</td>
          <td>Francisco Chang</td>
          <td>Mexico</td>
        </tr>
        <tr>
          <td>Ernst Handel</td>
          <td>Roland Mendel</td>
          <td>Austria</td>
        </tr>
        <tr>
          <td>Island Trading</td>
          <td>Helen Bennett</td>
          <td>UK</td>
        </tr>
        <tr>
          <td>Laughing Bacchus Winecellars</td>
          <td>Yoshi Tannamuri</td>
          <td>Canada</td>
        </tr>
        <tr>
          <td>Magazzini Alimentari Riuniti</td>
          <td>133</td>
          <td>152</td>
        </tr>
      </table>
    </div>
    <div class="teas">
    <h1>Teas</h1>
<hr>
      <table>
        <tr>
          <th>Company</th>
          <th>Contact</th>
          <th>Country</th>
        </tr>
        <tr>
          <td>Alfreds Futterkiste</td>
          <td>Maria Anders</td>
          <td>Germany</td>
        </tr>
        <tr>
          <td>Centro comercial Moctezuma</td>
          <td>Francisco Chang</td>
          <td>Mexico</td>
        </tr>
        <tr>
          <td>Ernst Handel</td>
          <td>Roland Mendel</td>
          <td>Austria</td>
        </tr>
        <tr>
          <td>Island Trading</td>
          <td>Helen Bennett</td>
          <td>UK</td>
        </tr>
        <tr>
          <td>Laughing Bacchus Winecellars</td>
          <td>Yoshi Tannamuri</td>
          <td>Canada</td>
        </tr>
        <tr>
          <td>Magazzini Alimentari Riuniti</td>
          <td>133</td>
          <td>152</td>
        </tr>
      </table>
    </div>  
    <div class="desserts">
      <h1>Desserts</h1>
<hr>
      <table>
        <tr>
          <th>Company</th>
          <th>Contact</th>
          <th>Country</th>
        </tr>
        <tr>
          <td>Alfreds Futterkiste</td>
          <td>Maria Anders</td>
          <td>Germany</td>
        </tr>
        <tr>
          <td>Centro comercial Moctezuma</td>
          <td>Francisco Chang</td>
          <td>Mexico</td>
        </tr>
        <tr>
          <td>Ernst Handel</td>
          <td>Roland Mendel</td>
          <td>Austria</td>
        </tr>
        <tr>
          <td>Island Trading</td>
          <td>Helen Bennett</td>
          <td>UK</td>
        </tr>
        <tr>
          <td>Laughing Bacchus Winecellars</td>
          <td>Yoshi Tannamuri</td>
          <td>Canada</td>
        </tr>
        <tr>
          <td>Magazzini Alimentari Riuniti</td>
          <td>133</td>
          <td>152</td>
        </tr>
      </table>
    </div>


    </div>
   </div>
  </div>
</body>

</html>


<style>

</style>

<div class="footer2">
  <div id="total">Total</div>
  </div>


<footer class="footer">
  <div class="summary">
  <table>

<div id="totalCalories">Total Calories: <span id="total"></span></div>  
<div id="totalCalories1">





        <tr>
          <th>Total Carbs: </th>
          <th>Total Fat: </th>
          <th>Total Protein: </div></th>
        </tr>
        <tr>
          <td class="bigtext"><span id="totalCarbs">0</span> G</td>
          <td class="bigtext"><span id="totalFats">0</span> G</td>
          <td class="bigtext"><span id="totalProteins">0</span> G</td>
    </div>
        </tr>
  </table>

</footer>


</body>


</html>

和css

html {
  height: 100%;
}

#contenttable {min-height:100%; height:100%}

body {
  display: flex;
  flex-direction: column;
  height: 100vh;
  /* Avoid the IE 10-11 `min-height` bug. */
}

.content {
  /* Prevent Chrome, Opera, and Safari from letting these items shrink to smaller than their content's default minimum size. */
  padding: 20px;
  background: url('http://www.padthai.decorolux.com/wp-content/uploads/2017/11/b2317ea3.png');
  flex: 1 0 auto;
  min-height:1000px;

}

.footer {
  flex-shrink: 0;
  /* Prevent Chrome, Opera, and Safari from letting these items shrink to smaller than their content's default minimum size. */
  padding: 40px;
  height:20%;
  position: fixed;
  width:100%;
  bottom: 0;
}

.footer2 {
  flex-shrink: 0;
  /* Prevent Chrome, Opera, and Safari from letting these items shrink to smaller than their content's default minimum size. */
  padding: 20px;
  padding-left: 40px;
  height:10%;
  background: url('http://www.padthai.decorolux.com/wp-content/uploads/2017/11/da9cc825.png');
    position: fixed;
    bottom: 20%;
    width:100%;
}


button {background: none; color: #424040; border-radius:0px;border:none; font-family: "Lithos Pro"; margin: auto auto;cursor:pointer;}

.base .ingredient .container  {font-size:1.2em;}




button p {margin: auto auto;}

h1, h2 {font-family: "Lithos Pro"; text-align:center; margin: 0 0 20px 0; color: #424040}

a {
  text-decoration: none;
  color: white;
}

* {
  box-sizing: border-box;
}


p {
  margin: 0 0 20px 0;
}

footer {
  background: url('http://www.padthai.decorolux.com/wp-content/uploads/2017/11/c4b0e511.png');
  color: white;
}

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
  float:left; 
  margin:1em auto;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: center;
  padding: 8px;
  font-family:lithos pro;

}

th {font-size:0.8em;}

tr:nth-child(even) {
  background-color: #dddddd;
}

ul,
li {
  text-decoration: none;
  list-style: none;
  margin: 3%;
  margin-bottom: 5%;
  width: auto;
}

.maindish, .soups, .desserts, .teas ,.summary {max-width:70%; margin:0 auto; display:block; height:100%; min-height: 600px;}

img {
  width:130px; height:120px; margin:0 auto; display:block;border-radius: 50%; padding: 5px;

}

#menuitems {
  display: flex;
  width: auto;
  margin: 0%;
  margin-bottom: 2%;
  align-items: center;
  justify-content: center;
  color: white;
  text-decoration: none;
  background: url('http://www.padthai.decorolux.com/wp-content/uploads/2017/11/b2317ea3.png')
  }

#total, #carbs {color:white; font-size:1.7em;}

/* Hover Animacio */

.image {
  opacity: 1;
  display: block;
  transition: .5s ease;
  backface-visibility: hidden;

}

.middle {
  position: absolute;
  transition: .5s ease;
  opacity: 0;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%)
}

.container:hover .image {
  opacity: 0.3;
}

.container:hover .middle {
  opacity: 1;
}

.text {
  background-color: #4CAF50;
  color: white;
  font-size: 16px;
  padding: 16px 32px;
}

.clicked {  

  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100%;
  width: 100%;
  opacity: 1;
  transition: .5s ease;
  background-color: #6FC0BB;
}

.bigtext {font-size: 1.3em !important;}
.smalltext {font-size: 0.45em;}
#totalCalories {font-size:1.5em; font-family: "lithos pro"}

和js

// if ($(".maindish, .soups, .desserts, .teas").is(":visible")) {
//
// }

$(".maindish, .soups, .desserts, .teas").hide();

//Main dish

$("#maindish").click(function() {
  var visibility = $(".maindish").is(":visible");
  if (visibility) {
    console.log("not visible");
  } else {
    console.log("visible");
  }
  //$(".soup, .desserts, .teas").hide();
  $(".maindish").slideToggle("fast");
  $(".soups, .desserts, .teas").slideUp();
});

//soup

$("#soups").click(function() {
  var visibility = $(".soups").is(":visible");
  if (visibility) {
    console.log("not visible");
  } else {
    console.log("visible");
  }
  $(".maindish, .desserts, .teas").slideUp();
  $(".soups").slideToggle("fast");
});

//teas

$("#teas").click(function() {
  var visibility = $(".teas").is(":visible");
  if (visibility) {
    console.log("not visible");
  } else {
    console.log("visible");
  }
  $(".maindish, .desserts, .soups").slideUp();
  $(".teas").slideToggle("fast");
});

//desszerts

$("#desserts").click(function() {
  var visibility = $(".desserts").is(":visible");
  if (visibility) {
    console.log("not visible");
  } else {
    console.log("visible");
  }
  $(".maindish, .teas, .soups").slideUp();
  $(".desserts").slideToggle("fast");
});


$(document).ready(function() {
  $(".ingredient").click(function() {
    var calories = $(this).data("calories");
    var carbs = $(this).data("carbs");
    var fat = $(this).data("fat");
    var proteins = $(this).data("proteins");
    var totalNum = $("#total");
    var totalCarbs = $("#totalCarbs");
    var totalFats = $("#totalFats");
    var totalProteins = $("#totalProteins");
    var currentCalories = +totalNum.html();
    var currentCarbs = +totalCarbs.html();
    var currentFats = +totalFats.html();
    var currentProteins = +totalProteins.html();
    var pressed = $(this).hasClass("clicked");

    if (pressed) {
      $(this).removeClass("clicked");
      totalNum.text(+(currentCalories - calories).toFixed(1));
      totalCarbs.text(+(currentCarbs - carbs).toFixed(1));
      totalFats.text(+(currentFats - fat).toFixed(1));
      totalProteins.text(+(currentProteins - proteins).toFixed(1));
    } else {
      $(this).addClass("clicked");
      totalNum.text(+(currentCalories + calories).toFixed(1));
      totalCarbs.text(+(currentCarbs + carbs).toFixed(1));
      totalFats.text(+(currentFats + fat).toFixed(1));
      totalProteins.text(+(currentProteins + proteins).toFixed(1));
    };

  });

});

为了方便起见,这里是 Codepen:

https://codepen.io/Pbalazs89/full/eyGXeN

【问题讨论】:

  • 这通常发生在您认为您正在对intfloat 进行操作时,但在不知不觉中您实际上正在对stringint 进行操作.. ..所以请确保您正在投射并验证您认为输入与您认为的一样
  • 我看不到错误,它在 chrome 上运行良好
  • 您是否尝试过对值进行console.log()?让您知道发生了什么?
  • 您尚未将 html 解析为数字,因此您将 2 个字符串加在一起尝试var currentCalories = parseFloat(totalNum.text());。我可能也会使用文本而不是 html。其他的工作是因为您从数据中获取它们,并且 jquery 足够聪明,可以将它们解析为正确的格式。 + 你在+totalCarbs.html() 之类的东西前面加了什么?
  • @Pete 这是一个一元运算符,显然是将某些内容转换为数字的最快和首选方式。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

标签: javascript jquery html css nan


【解决方案1】:

我添加了一个检查来查看 currentCalories 是否为数字,如果不是,则将其变为 0,这样,您就不会以“total”作为 currentCalories 开头:

$(document).ready(function() {
  $(".ingredient").click(function() {
    var calories = $(this).data("calories");
    var carbs = $(this).data("carbs");
    var fat = $(this).data("fat");
    var proteins = $(this).data("proteins");
    var totalNum = $("#total");
    var totalCarbs = $("#totalCarbs");
    var totalFats = $("#totalFats");
    var totalProteins = $("#totalProteins");
    var currentCalories = +totalNum.html();
    var currentCarbs = +totalCarbs.html();
    var currentFats = +totalFats.html();
    var currentProteins = +totalProteins.html();
    var pressed = $(this).hasClass("clicked");

    if(isNaN(currentCalories)){
      currentCalories = 0;
    }

    if (pressed) {
      $(this).removeClass("clicked");
      totalNum.text(+(currentCalories - calories).toFixed(1));
      totalCarbs.text(+(currentCarbs - carbs).toFixed(1));
      totalFats.text(+(currentFats - fat).toFixed(1));
      totalProteins.text(+(currentProteins - proteins).toFixed(1));
    } else {
      $(this).addClass("clicked");
      totalNum.text(+(currentCalories + calories).toFixed(1));
      totalCarbs.text(+(currentCarbs + carbs).toFixed(1));
      totalFats.text(+(currentFats + fat).toFixed(1));
      totalProteins.text(+(currentProteins + proteins).toFixed(1));
    };

  });

我还建议您解析所有将在和/减法中的值,以确保所有都是真正的数字,如果不是,则将其转换为零,这将确保计算时不会出错。

https://codepen.io/anon/pen/vpewJL

【讨论】:

    【解决方案2】:

    问题是当您的程序第一次运行时,它会将 currentCalories 变量设置为“Total”

    var totalNum = $("#total");
    totalNum.html();
    

    由于文本为 Total,因此变为“Total”

    <div id="total">Total</div>
    

    应该是

    <div id="total">0</div>
    

    【讨论】:

    • $("#total"); 不等于文本。它是对 Jquery 对象的引用。另一方面,$("#total").text(); 等同于文本。
    • 您好,感谢您的提示。不幸的是,它只能部分解决问题。如果我使用您的编辑,我单击的第一个项目将很好地显示值。但是,如果我单击第二个项目,它会再次进入 NaN :( 无法弄清楚是什么原因造成的。我在较旧的计算中使用了这个最奇怪的部分,它在那里工作:codepen.io/Pbalazs89/full/LeEyMm
    【解决方案3】:

    在我的代码中遇到了同样的问题,并通过使用“on”方法而不是直接使用“click”来修复它。

    【讨论】:

    • 点评来源: 嗨,这篇文章似乎没有为问题提供quality answer。请编辑您的答案并改进它,或者将其作为评论发布。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    相关资源
    最近更新 更多