简体   繁体   English

从函数内集成变量

[英]Integrate a variable from within a function

I am having troubles getting the total hours needed depending on method of transport. 根据运输方式,我无法获得所需的总时数。

This is my first code as a lesson to familiarize myself with coding. 这是我的第一门代码,它是使自己熟悉编码的课程。

Javascript: 使用Javascript:

$(document).ready(function() {

$('#calculateTotal').click(function () {


var a = ($('#car').val()) ? parseInt($('#car').val()) : 0;

var c = ($('#bus').val()) ? parseInt($('#bus').val()) : 0;


 document.getElementById("qr1").onclick = function() {
    if (this.checked) {
        var b = 1;
    }
    else {
        b = 0;
    }
};

var totalTime = a+b+c;

$('#total').html(totalTime);


});

});

var b is not being recognized as a variable when I click on Calculate Total. 当我单击“计算总计”时,var b未被识别为变量。 Can anyone show me the way as to how to declare var b in a way that makes sense in coding? 谁能告诉我如何以一种在编码中有意义的方式声明var b?

Thank you. 谢谢。

You are declaring "b" inside of a function. 您在函数内部声明了“ b”。

Because you want it to be globaly accessible outside of the function it was created in, remove the var from in front of it in the first statement. 因为您希望它在创建它的函数之外可以全局访问,所以在第一个语句中从其前面删除var

document.getElementById("qr1").onclick = function() {
    if (this.checked) {
        b = 1;
    }
    else {
        b = 0;
    }
};

Alternatively you could set b outside of the function to 0 或者,您可以将函数之外的b设置为0

b = 0; b = 0;

then 然后

document.getElementById("qr1").onclick = function() {
    if (this.checked) {
        b = 1;
    }
};

As an aside, global s are usually frowned upon (I use them a lot) so you could create an object to house everything. 顺便说一句,global通常不被接受(我经常使用它们),因此您可以创建一个对象来容纳所有内容。 This way you are nice and tidy. 这样,您就很整洁。

Also, as mentioned in the comments, the qr1 click handler should be placed outside of the calculate total function. 另外,如评论中所述,qr1单击处理程序应放在calculate total函数之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM