jquery - 我试图在 jQuery : 中划分两个变量

标签 jquery html

您可以查看此jsfiddle中的代码.

$(document).ready(function() {
  $('#product').change(function() {
  $('#result').text($(this).val() * 6);
});

$('#product1').change(function() {
  var num1 = $('#result');
  var num2 = $('#product1');
  var result1 = parseFloat(num1, 10) / parseFloat(num2, 10);
  $("#result1").text(result1);
  console.log(typeof(result1));
 });
});
<div class="container">
 <div class="col-xs-6">
  Count<input name="shares" id="product" type="number" / min="0">
 </div>
</div>

<div>
  Total Value: <span id="result"></span>/
  <input name="shares1" id="product1" type="number" / min="0">
  <br /> Final Result: <span id="result1"></span>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

当我尝试除以两个变量时,结果字段中出现 NaN

请帮我解决这个问题。提前致谢。

最佳答案

您正在解析 jquery 对象,而不是它的值/文本。

  var num1 = $('#result').text();
  var num2 = $('#product1').val();

Internally ,parseFloat 会首先尝试将传递的参数转换为字符串。因此,将调用该对象的 toPrimitive 并返回其默认原始值。例如:“[对象对象]”。所以当转换非数字字符串时会导致NaN。因此 NaN/NaN 等于 NaN

关于jquery - 我试图在 jQuery : 中划分两个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36809955/

相关文章:

javascript - 如何使此点击实例仅发生一次并可供所有内容访问?

jquery - 如何序列化当前表单?

css - 在 CSS 中定位 Picture 元素时,我们应该使用 img 还是图片选择器?

javascript - 自定义的 Javascript 函数没有像我预期的那样工作?

javascript - 从字符串中提取数字并删除小数并将其添加到字符串中

javascript - JQuery - 如何在每次按下按钮时创建一个新的可拖动 div

html - 使用固定高度滚动时的额外空间

javascript - 检查文本框

html - 一些奇怪的布局只使用不同高度的 ul/li 元素

javascript - 触发子级点击但阻止事件传播到父级