2017-08-28 122 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" 
     }); 
}); 
});