var txta=...不寫(xiě)在函數(shù)代碼{}里面,最后document.get...也不寫(xiě)在函數(shù)代碼{}里面
<!DOCTYPE html>
<html>
?<head>
? <title> 事件</title>??
? <script type="text/javascript">
? ? var txta=document.getElementById("txt1").value;
? ? var txtb=document.getElementById("txt2").value;
? ? var txtc=document.getElementById("select").value;
? ? var result;
? ? function count(){
? ? ? ? switch(txtc){
? ? ? ? ? ? case "+":result=parseInt(txta)+parseInt(txtb);break;
? ? ? ? ? ? case "-":result=txta-txtb;break;
? ? ? ? ? ? case "*":result=txta*txtb;break;
? ? ? ? ? ? case "/":result=txta/txtb;break;
? ? ? ? ? ? }
? ?}
? ? document.getElementById("fruit").value=result;
? </script>?
?</head>?
?<body>
? ?<input type='text' id='txt1' />?
? ?<select id='select'>
<option value='+'>+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
? ?</select>
? ?<input type='text' id='txt2' />?
? ?<input type='button' value=' = ' onclick="count()"/> <!--通過(guò) = 按鈕來(lái)調(diào)用創(chuàng)建的函數(shù),得到結(jié)果-->?
? ?<input type='text' id='fruit' />? ?
?</body>
</html>
我知道開(kāi)頭var txta=document.等等和結(jié)尾document.getElementById("fruit").value=result;這兩東西必須寫(xiě)在函數(shù)代碼{}里才是對(duì)的,我想知道為什么這樣子它就錯(cuò)了,觸犯了哪個(gè)原理?
2019-08-28
寫(xiě)在外面,沒(méi)點(diǎn)擊按鈕就運(yùn)行函數(shù)之外的代碼,此時(shí)那些框框里沒(méi)有任何用戶輸入的數(shù)據(jù),value為空,同理,result尚未被賦值。
靠網(wǎng)友是不行的,還是得自己摸索。
2019-08-27
我大概知道原因了,是不是瀏覽器是按照先后順序執(zhí)行代碼的,函數(shù)里的代碼需要點(diǎn)擊才能執(zhí)行,那兩個(gè)東西在外面的話,早就被執(zhí)行了
2019-08-27
代碼的執(zhí)行是有先后順序的,先執(zhí)行script里面的(函數(shù)是調(diào)用時(shí)才執(zhí)行),所以你寫(xiě)在函數(shù)外面的部分會(huì)比body部分先執(zhí)行,由于body部分還沒(méi)有執(zhí)行,所以還沒(méi)有id為txt1的標(biāo)簽,所以document.getElementById("txt1").value根本得不到,所以會(huì)錯(cuò)誤。
2019-08-27
寫(xiě)在外面函數(shù)switch就沒(méi)辦法獲取到txt1 txt2 selec的值了,個(gè)人是這么理解的,初學(xué)者勿噴