為什么使用btn.onlick = count(); 進入頁面就觸發事件
function count(){
? ? ??
? ? ? var txt1 = parseInt(document.getElementById('txt1').value); //獲取第一個輸入框的值
? ? var txt2 = parseInt(document.getElementById('txt2').value); //獲取第二個輸入框的值
? ? var val = document.getElementById('select').value; //獲取選擇框的值
? ? var showfruit = document.getElementById('fruit');?
? ? //獲取通過下拉框來選擇的值來改變加減乘除的運算法則
? ? ? //設置結果輸入框的值
? ? ?
? ? ? switch(val){
? ? ? ? case '+':
? ? ? ? ? ? showfruit.value = txt1 + txt2;
? ? ? ? ? ? console.log(txt1 + txt2);
? ? ? ? ? ? break;
? ? ? ? case '-':
? ? ? ? ? ? showfruit.value = txt1 - txt2;
? ? ? ? ? ? break;
? ? ? ? case '*':
? ? ? ? ? ? showfruit.value = txt1 * txt2;
? ? ? ? ? ? break;
? ? ? ? case '/':
? ? ? ? ? ? showfruit.value = txt1 / txt2;
? ? ? ? ? ? break;
? ? ? }
? };
? var btn = document.getElementById( 'getresult' );?
? btn.onlick = count(); // 用這種方法執行,為什么進入頁面就會出發事件?
2017-07-24
因為count();這種寫法是直接調用 count方法,也就是count函數已經在onclick事件觸發之前就已經被執行了,正確的寫法是 onclick=conut;這樣才能做到onclick事件觸發后 才調用count;關鍵點就是 方法后面加個()就是直接調用;
2017-07-20
是onclick事件吧