JavaScript 事件 編程練習

來源:互聯網
上載者:User

標籤:

編程練習

使用JS完成一個簡單的計算機功能。實現2個輸入框中輸入整數後,點擊第三個輸入框能給出2個整數的加減乘除。

提示:擷取元素的值設定和擷取方法為:例:賦值:document.getElementById(“id”).value = 1; 取值:var = document.getElementById(“id”).value;

任務

第一步: 建立構建運算函數count()。

第二步: 擷取兩個輸入框中的值和擷取選擇框的值。

提示:document.getElementById( id名 ).value 擷取或設定 id名的值。

第三步: 擷取通過下拉框來選擇的值來改變加減乘除的運演算法則。

提示:使用switch判斷運演算法則。

第四步:  通過 = 按鈕來調用建立的函數,得到結果。

注意: 使用parseInt()函數可解析一個字串,並返回一個整數。

 

<!DOCTYPE html>
<html>
<head>
<title> 事件</title>
<script type="text/javascript">
function count(){
var s;
//擷取第一個輸入框的值
var one=document.getElementById("txt1").value;
//擷取第二個輸入框的值
var two=document.getElementById("txt2").value;
//擷取選擇框的值
var sel=document.getElementById("select").value;
//擷取通過下拉框來選擇的值來改變加減乘除的運演算法則
switch(sel){
case "+":s=parseInt(one)+parseInt(two);
break;
case "-":s=parseInt(one)-parseInt(two);
break;
case "*":s=parseInt(one)*parseInt(two);
break;
case "/":s=parseInt(one)/parseInt(two);
}
//設定結果輸入框的值
document.getElementById("fruit").value=s;
}
</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()" /> <!--通過 = 按鈕來調用建立的函數,得到結果-->
<input type=‘text‘ id=‘fruit‘ />
</body>
</html>

JavaScript 事件 編程練習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.