简体   繁体   中英

innerHTML in function (Global variables?)

I'm struggling to get this working. The dispatch() function seems to be getting triggered (tested with the alert), but the innerHTML lines don't seem to work.

Also, i doesn't seem to increase despite the i++ in the onSubmit .

Here is the function in question:

function dispatch(passengers,i,timesArray)
{
    alert('value of i is '+i);
    timesArray[i]=getTime();

    var avTime=getAverageTime(timesArrary);

    var throughput=passengers*3600000/avTime;

    if(i==0)
    {
        document.getElementById('output').innerHTML = 'Calculating...';
    }
    else
    {
        document.getElementById('output').innerHTML = throughput;
    }
    //and possibly a list (w/e)
}

And here is the form:

<form method="post" action="javascript:void(0);" name="applesForm" onSubmit="dispatch(document.applesForm.numPassengers.value, num, times);i++;">
    <input type="text" name="numApples" id="numPassengers" />
    <br/>
    <input type="submit" name="Submit" value="Press on Dispatch!"/>
</form>

Could this be a question of not being able to change global variables from inside the function?

Or, is there something wrong with the avTime or throughput lines which is making the function cease?

Thanks.

In this line:

<form method="post" action="javascript:void(0);" name="applesForm" onSubmit="dispatch(document.applesForm.numPassengers.value, num, times);i++;">

i is a global variable, but in dispatch() i is an argument which is not in global scope. Inside dispatch() it is in local scope of that function, and can't be increased in global scope. Hence I think your onSubmit() should be:

onSubmit="dispatch(document.applesForm.numPassengers.value, num, times);num++;">

Why is the variable being increased outside the function? Shouldn't it be inside the function and increased there?

Also, if num is global, you don't need to pass it as a parameter.

// global
var num = 0;

function dispatch(passengers, timesArray)
{
    alert('value of num is ' + num);
    timesArray[num]=getTime();

    var avTime = getAverageTime(timesArrary);

    var throughput = passengers * 3600000 / avTime;

    if(num == 0)
    {
         document.getElementById('output').innerHTML = 'Calculating...';
    }
    else
    {
        document.getElementById('output').innerHTML = throughput;
    }
    //and possibly a list (w/e)

    // increasing num here!
    num++;
}

Then your form could drop the increase in the variable, and the num from the call.

<form method="post" action="javascript:void(0);" name="applesForm" onSubmit="dispatch(document.applesForm.numPassengers.value, times)">

Cheers, Apoc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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