2016-10-19 32 views
0
<p>Enter some text</p> 
<form> 
<input type="text" id="userInput"> 
<button onclick="log();">Go!</button> 
</form> 

<script> 
function log() { 
    var input = document.getElementById("userInput").value; 
    console.log(input); 
} 
</script> 

當我點擊按鈕時,它刷新頁面,清除日誌。我最初嘗試使用<input type="submit">,但是當我點擊任何類型的按鈕時,它刷新。我將如何阻止這一點?HTML JS錯誤記錄輸入

+0

使用'類型=「按鈕」'這個按鈕,因此它不提交表單 –

+0

替代關鍵是要設置的變量的onsubmit形式如下:'

onsubmit =「return false」> ....
' – Gabrio

回答

0

嘗試:

<p>Enter some text</p> 
<form action="" method=""> 
    <input name="userInput" type="text" id="userInput" /> 
    <button type="button" onclick="log()">Go!</button> 
</form> 

<script> 
    function log() { 
     var input = document.getElementById("userInput").value; 
     console.log(input); 
     return false; 
    } 
</script> 

只會增加return false你的js。 瞭解stopPropagation

0

很難說清楚你的例子,但一般情況下,如果你試圖阻止某個動作執行類似於執行默認行爲的頁面刷新操作,則可以在事件處理函數上使用preventDefault方法。所以,你的功能將成爲

function log(e) { // passing in the event to the handler as "e" 
    var input = document.getElementById("userInput").value; 
    console.log(input); 
    e.preventDefault(); 
} 

編輯: 更新與帕特里克記的筆記,雖然我還沒有看到的片斷,試圖刷新頁面,甚至沒有任何type屬性,或buttonsubmit類型。

<p>Enter some text</p> 
 
<form action="" method=""> 
 
    <input name="userInput" type="text" id="userInput" /> 
 
    <button onclick="log(event)">Go!</button> 
 
</form> 
 

 
<script> 
 
    function log(e) { 
 
     var input = document.getElementById("userInput").value; 
 
     console.log(input); 
 
     e.preventDefault() 
 
    } 
 
</script>

+0

不行,沒有工作。 –

+0

@HughChalmers - 查看我的編輯 - 我沒有看到您的代碼嘗試在代碼片段中進行刷新 - 您的頁面中是否還有其他內容? –

+1

@anied,OP的按鈕上沒有'type =「button」'屬性,這就是爲什麼你的表單不會嘗試在你的代碼段中提交。當使用'onclick'屬性時'log()'不會自動獲取'event'對象,它將需要改爲'onclick =「log(event)」' –

0
<p>Enter some text</p> 
<form> 
    <input type="text" id="userInput"> 
    <button type="button" onclick="log();">Go!</button> 
</form> 

<script> 
    function log() { 
     var input = document.getElementById("userInput").value; 
     console.log(input); 
    } 
</script> 

所以只需添加類型=「按鈕」