![](/img/trans.png)
[英]Why my Asp button doesn't works even i added Onclick Event inside modal popup?
[英]I'm unsure as to why my onclick button doesn't link up with what I type into my textbox?
因此,我對Java語言還很陌生,我正在研究一些將十進制數字轉換為二進制數字的代碼。 但是,當我運行該程序時,似乎無法獲得所需的輸出。 我做的最好的事情就是讓我的函數輸出已經在函數內部的確切數字,而我卻想獲取從鍵入文本框的任何數字生成的輸出? 我不完全確定我在哪里出錯。 我覺得我顯然缺少某些東西,但是我似乎無法確切地了解它到底是什么。 我一直在使用codecademy和w3schools來獲取有關JavaScript的更多知識,但是如果任何人在他們開始編程時都擁有其他幫助他們的資源,那將是很棒的!
<!DOCTYPE html>
<html>
<body>
<p>Convert from Decimal to Binary:</p>
<form method = "post">
<p id = "demo">
<label for="decNum"></label>
<input name="decNum" type="text">
<button onclick="toBinary()">Enter</button>
</p>
</form>
<script>
function toBinary() {
document.getElementById("demo").innerHTML =
parseInt(num,10).toString(2);
}
</script>
</body>
</html>
這是因為num
沒有值。
嘗試這個:
<p>Convert from Decimal to Binary:</p>
<form method = "post">
<p id = "demo">
<label for="decNum"></label>
<input name="decNum" type="text" id="decNum">
<button onclick="toBinary()">Enter</button>
</p>
</form>
<script>
function toBinary() {
var num = document.getElementById("decNum").value;
document.getElementById("demo").innerHTML =
parseInt(num, 10).toString(2);
}
</script>
我會改變一些事情。 首先,我將非表單元素保留在表單之外。 主要問題是num沒有值,但是要確保它有效,您還需要獲取事件並使用event.preventDefault()來確保它不提交表單。 嘗試:
<!DOCTYPE html>
<html>
<body>
<p>Convert from Decimal to Binary:</p>
<form method="post">
<label for="decNum"></label>
<input id="field" name="decNum" type="text">
<button onclick="toBinary(event)">Enter</button>
</form>
<p id="demo"></p>
<script>
function toBinary(event) {
event.preventDefault();
var value = document.getElementById('field').value;
document.getElementById("demo").innerHTML =
parseInt(Number(value), 10).toString(2);
}
</script>
</body>
</html>
您沒有定義num
。
這樣從輸入中獲取它:
function toBinary() { const num = document.getElementById("textInput").value; document.getElementById("demo").innerHTML = parseInt(Number(num),10).toString(2); }
<p id = "demo"></p> <label for="decNum"></label> <input name="decNum" type="text" id="textInput"> <button onclick="toBinary()">Enter</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.