2016-11-18 65 views
1

爲什麼這行JS代碼返回錯誤「無法設置屬性......未定義」?Javascript:error can not set property'...'undefined

document.forms["myForm"]["english_error"].textContent = "English sentence is required"; 

我正確地引用了div元素的id。

<input type="text" id="english" name="english" placeholder="English sentence" /> 
<div id="english_error" class="val_error"></div> 
+2

假設這些元素在'myForm',不所有具有ID的元素都將顯示爲「form」元素的屬性。主要形成控制意願。 – 2016-11-18 21:48:10

+1

可能重複[如何引用DIV發送JavaScript調用ID?](http://stackoverflow.com/questions/9517003/how-to-reference-id-of-div-sending-javascript-call) – DDrake

回答

0

我不能發表評論,但還沒有這可能是一個重複: How to reference ID of DIV sending JavaScript call?

document.getElementById("english_error").textContent = "English sentence is required"; 
+0

我wouldn不要認爲這是重複的。我沒有看到與其他問題有很多關聯。 – Marcs

1

只有表單控件映射,基本上只<input><textarea><select>標籤:

var sentence = document.forms["myForm"]["english"]; 

<input>標籤所以這個工程:

document.forms["myForm"]["english_error"].textContent = "English sentence is required"; 

english_error是正常<div>這樣是不行的,你必須使用:

document.getElementById("english_error").textContent = "English sentence is required"; 

並且還通過類名:

document.getElementsByClassName("val_error")[0].textContent = "English sentence is required";