[英]JavaScript function doesn't seem to work consistently
我正在嘗試創建一個動態菜單,只有在前一個問題得到解答后才會顯示某些問題。 我已經讓它為其中一個問題工作,但下一個拋出錯誤Uncaught TypeError: Cannot read property 'length' of undefined
,即使代碼實際上是相同的。
這是我正在調用的JavaScript函數:
// displays div when input is not empty
function showOnInput(div, input) {
let x = document.getElementById(`${input}`);
let y = document.getElementById(`${div}`);
if (x.value.length > 0) {
y.style.display = 'block';
} else {
y.style.display = 'none';
}
}
這里是調用它的HTML代碼:
<div id="customizeChar" class="text">
<form>
<div id="name">
<label>What is your character's name?</label>
<br>
<input v-model="fname" id="fname" placeholder="First Name" onkeyup="showOnInput('age', 'fname')">
<input v-model="lname" id="lname" placeholder="Last Name">
</div>
<br>
<div id="age" style="display: none">
<label>How old is {{fname}} {{lname}}?</label>
<br>
<input v-model="age" id="age" placeholder="Age" onkeyup="showOnInput('sex', 'age')">
<label style="font-size: 80%">years old</label>
</div>
<br><br>
<div id="sex" style="display: none">
<label>Is {{fname}} a male or female?</label>
<br>
<select v-model="sex">
<option>Male</option>
<option>Female</option>
</select>
</div>
</form>
</div>
隱藏age
塊,直到在name
塊中給出輸入,如預期的那樣,但是在age
塊中輸入答案然后拋出Uncaught TypeError
錯誤。
我能夠使用Vue的v-if
指令讓它做我想做的事。 這是最終的HTML:
<div id="customizeChar" class="text">
<form>
<div id="name">
<label>What is your character's name?</label>
<br>
<input v-model="fname" id="fname" placeholder="First Name">
<input v-model="lname" id="lname" placeholder="Last Name">
</div>
<br>
<div id="age" v-if="fname != ''">
<label>How old is {{fname}} {{lname}}?</label>
<br>
<input v-model="age" id="age" placeholder="Age">
<label style="font-size: 80%">years old</label>
</div>
<br><br>
<div id="sex" v-if="age != ''">
<label>Is {{fname}} a male or female?</label>
<br>
<select v-model="sex">
<option>Male</option>
<option>Female</option>
</select>
</div>
</form>
</div>
如果我能做出改進,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.