2017-08-28 121 views
-1

我有一個帶有提交按鈕的表單,並希望在單擊時更改該按鈕的顏色。事件監聽器更改按鈕

我在HTML試過這樣:

const myButton = document.getElementById("submitButton"); 
 

 
myButton.addEventListener("submit", function() { 
 
    myButton.style = "background:blue" 
 
})
<div> 
 
    <form id="connexion"> 
 
    <input type="text" placeholder="Pseudo" /> 
 
    <button id="submitButton" type="submit" value="Go" style="background:yellow"></button> 
 
    </form> 
 
</div>

它不工作。 你能告訴我問題在哪裏嗎?
謝謝

+2

按鈕沒有'submit'事件,表單可以。 – zzzzBov

回答

1

要麼將​​submit更改爲click要麼將​​eventListener添加到您的表單中。這裏與表單上的的事件監聽:

const myButton = document.getElementById('submitButton'); 
 
const myForm = document.getElementById('connexion'); 
 

 
myForm.addEventListener('submit', function(e) { 
 
    e.preventDefault(); 
 
    myButton.style = 'background:blue'; 
 
})
<div> 
 
    <form id="connexion"> 
 
    <input type="text" placeholder="Pseudo" /> 
 
    <button id="submitButton" style="background:yellow">Go</button> 
 
    </form> 
 
</div>

2

按照zzzzBov的評論:按鈕沒有submit事件。

您需要在提交表單event.preventDefault();時阻止默認表單操作。並設置風格background-color與按鈕ID:

document.getElementById("submitButton").style = "background: blue;"; 

可以執行submit事件與形式ID。

事情是這樣的:

const connexion = document.getElementById("connexion"); 
 

 
connexion.addEventListener("submit", function(e) { 
 
    e.preventDefault(); 
 
    document.getElementById("submitButton").style = "background: blue;"; 
 
});
<form id="connexion"> 
 
    <input type="text" placeholder="Pseudo" /> 
 
    <button id="submitButton" type="submit" style="background: yellow;">Go</button> 
 
</form>

1

按鈕沒有一個事件提交嘗試使用click代替:

<!DOCTYPE html> 
<html lang="fr"> 
<head> 
<meta charset="UTF-8"> 
<title>Test</title> 
</head> 
<body> 
<div> 
    <form id="connexion" > 
      <input type="text" placeholder="Pseudo" /> 
      <input id="submitButton" type="button" value="Go" style="background:yellow"></button> 
    </form> 
</div> 
<script type="text/javascript" src="main.js"></script> 
</body> 
</html> 

和jQuery的:

$(document).ready({ 
$("#submitButton").click(function(){ 
     $(this).css({ 
      "background-color":"blue" 
     }); 
}); 
});