为什么会出现此Javascript错误”未定义连接”?

Why am I getting this Javascript error “connection is not defined”?

我不确定为什么会出现此错误:

1
2
connection is not defined  
document.getElementById("flashTest").sendValFromHtml(connection.value);

这是我的代码:

1
2
3
4
5
6
7
8
9
10
11
function submitCheck() {
    var hasConnection = document.getElementById("formTest").connection.value.length != 0;
    var hasLocation = document.getElementById("formTest").location.value.length != 0;

    document.getElementById("connection").className = hasConnection ?"" :"invalid";
    document.getElementById("location").className = hasLocation ?"" :"invalid";

    if(hasConnection && hasLocation){
        document.getElementById("flashTest").sendValFromHtml(connection.value);
    }
}

HTML:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<form id="formTest" name="formTest" method="post" action="">
    <fieldset class="form">
       
            <label id="connection">Connection:*</label>
           
                <select name="connection">
                    <option value="">Select connection type</option>
                    <option value="dsl">DSL</option>
                    <option value="cable">Cable</option>
                    <option value="fibre">Fibre</option>
                </select>
           
       
       
            <label id="location">Location*:</label>
           
                <select name="location">
                    <option value="">Select your location</option>
                    <option value="home">At home</option>
                    <option value="work">At work</option>
                </select>
           
       
       
            <label>Postcode:</label>
           
                <input type="text" name="postcodeVal" id="postcodeVal">
           
       
         
        <input type="button" name="sendToFlash" id="sendToFlash" value="Start Test" onclick="submitCheck();" />

       
    </fieldset>
</form>


首先,将表单存储为局部变量:

1
var form = document.getElementById("formTest");

然后使用此局部变量而不是多次查询DOM:

1
2
var hasConnection = form.connection.value.length != 0;
var hasLocation = form.location.value.length != 0;

最后,在connection前面加上form.

1
document.getElementById("flashTest").sendValFromHtml(form.connection.value);

替换:

1
2
var hasConnection = document.getElementById("formTest").connection.value.length != 0;
var hasLocation = document.getElementById("formTest").location.value.length != 0;

具有:

1
2
var hasConnection = document.getElementById("connection").value.length != 0;
var hasLocation = document.getElementById("location").value.length != 0;


connection.value更改为:

1
document.forms.formTest.connection.value