var totalcostApple;
function shopping() {
$("#apple").on("keyup", function () {
var quantity = $("#apple").val();
totalcostApple = (quantity * 0.2).toFixed(2);
});
};
shopping();
console.log(totalcostApple);
答案 0 :(得分:0)
你似乎误解了自己在做什么。你的代码流程都搞砸了。当您调用shopping()
时,您指示浏览器将keyup事件绑定到apple对象。然而,在将它绑定到对象之后,您查询变量。但是你的速度不够快,无法在shopping
函数和keyup
事件之间生成密钥事件。只是为了向您展示,而不是仅仅一次登录控制台,尝试在其他时间将其记录到控制台。随时。添加以下代码行:
$(window).on('click', function(){ console.log(totalcostApple); });
现在,您可以在实际更改时测试。每次单击时,它都会将totalcostApple
的当前值记录到控制台。
但实际上,你应该改进你的代码:
// add some code to assure that everything you do only gets executed after the DOM is ready
$(document).ready(function(){
// add a default value to your totalcost.
var totalcostApple = 0;
function shopping() {
// remove your keyup event from here and tie it in directly.
var quantity = $("#apple").val();
totalcostApple = (quantity * 0.2).toFixed(2);
// move your log inside the event so you can see it when it *changes*
console.log(totalcostApple);
};
$("#apple").on("keyup", shopping);
});