[英]Why i'm getting [object object] using jQuery?
I have a function there i want to try sum two numbers using variable like given below, but i'm getting [object object] instead of total of sum. 我那里有一个函数,我想尝试使用如下所示的变量求和两个数字,但是我正在获取[object object]而不是总和。
var convenienceCharge = 100; var totalPgCost = 500; var subTotalPgCost = 0; function totalPgCostFunction() { subTotalPgCost += $('.subTotalPgCost').text(convenienceCharge + totalPgCost + 18); alert(subTotalPgCost); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="totalPgCostFunction();">Click</button>
.text
will return a object. .text
将返回一个对象。 that is why you are seeing [object object] 这就是为什么您看到[object object]
You need to do it like this. 您需要这样做。
var convenienceCharge = 100; var totalPgCost = 500; var subTotalPgCost = 0; function totalPgCostFunction() { subTotalPgCost += convenienceCharge + totalPgCost + 18; $('.subTotalPgCost').text(subTotalPgCost); alert(subTotalPgCost); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="totalPgCostFunction();">Click</button> <div class="subTotalPgCost"></div>
The issue is because when you call the setter of text()
it returns a jQuery object, hence the output you see. 问题是因为当您调用
text()
的setter时,它将返回一个jQuery对象,因此您会看到输出。
To make this work you need to split the calculation and text()
logic, like this: 为此,您需要拆分计算和
text()
逻辑,如下所示:
var convenienceCharge = 100; var totalPgCost = 500; var subTotalPgCost = 0; $(function() { $('button').click(function() { subTotalPgCost += convenienceCharge + totalPgCost + 18; $('.subTotalPgCost').text(subTotalPgCost); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button>Click</button> <div class="subTotalPgCost"></div>
Also note the use of an unobtrusive event handler in this example instead of the outdated on*
attribute. 还要注意,在此示例中使用了不显眼的事件处理程序,而不是过时的
on*
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.