iT邦幫忙

0

javascript botton onclick function issue

各位先進

有關 botton onclick function為何無法如預期般執行?

還請各位指點一番。

我於int1輸入2,int2輸入3,按Add botton,為何不是執行 function add(),

卻是執行 unhandled()?

下列HTML5 內容如下

<!DOCTYPE html>
<html>
<head>
<script>

function add() {
	alert($("#int1").val() + $("#int2").val());
}

function divide() {
	if (isNaN($("#int1").val()) || isNaN($("#int2").val())) {
	   throw('One or more values are non-numeric');
	}
	alert($("#int1").val() / $("#int2").val());
}

onerror = unhandled;
function unhandled(msg, url, line) {
	alert('There has been an unhandled exception.');
}
</script>
</head>
<body>

Integer 1: <input type="text" id="int1" /><br />
Integer 2: <input type="text" id="int2" /><br />
<input type="button" name="add" value="Add" onclick="add()" >
<input type="button" name="divide" value="Divide" onclick="divide()" >
</body>
</head>
</html>
看更多先前的討論...收起先前的討論...
fillano iT邦超人 1 級 ‧ 2016-08-15 14:53:31 檢舉
https://jsfiddle.net/dvdovfod/1/

腦補了一些內容...你貼的東西不完整,所以也很難判斷哪裡有問題
小財神 站方管理人員 ‧ 2016-08-15 15:26:02 檢舉
費大費心了,
我check發問者的提問內容,由於使用了 HTML Code,基於安全性考量,系統會濾掉,才會不完整。
我用程式碼區塊包起來,已正常顯示。
weiclin iT邦高手 4 級 ‧ 2016-08-15 16:39:57 檢舉
小財神還要負責修復沒貼好的代碼啊..你才真是辛苦了
fillano iT邦超人 1 級 ‧ 2016-08-16 09:37:33 檢舉
感謝小財神...
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
tzuchin
iT邦新手 5 級 ‧ 2016-08-15 15:49:05

你的code有用到jquery

$("#int1").val()

但你沒有引入@@..

tzuchin iT邦新手 5 級 ‧ 2016-08-15 15:58:19 檢舉

開發的時候記得要隨手開啟瀏覽器的"開發人員工具" (F12),主流瀏覽器都有支援,錯誤訊息一看就清楚~

感謝您的提醒,不過剛剛用F12看,一開始引入jquery後,訊息是TypeError: add is not a function.後來嘗試將它改為 add123後,可以執行了,但結果卻是 4 + 5 = 45;同理將divide改為divide123後8 / 4 = 2。不知 jquery 的 .val() 有何玄機,為何 + 和** /** 倆著有何不同?

解決了!!
加上parseInt就能讓文字轉成實數進而讓加號完成數字加法而非文字加法。而除法只能有數字除法,沒有文字除法。

function add123(){
	alert( **parseInt**($("#int1").val()) +** parseInt**($("#int2").val()) );
}

謝謝各位的協助。

我要發表回答

立即登入回答