我试图更改元素的innerhtml,但每次单击按钮时它都会一直重置为“ ddd”

<form>
<p id="passError">ddd</p>
<button id="submit">Login</button>
</form>

<script type="text/javascript">
document.getElementById("submit").onclick = function(){changeit()};
function changeit()
{
    pError = document.getElementById("passError");
    pError.innerHTML = ("wrong password");
</script>

最佳答案

首先,您在函数上缺少},然后通过提交,提交了必须防止的表单。您不需要changeit函数的包装函数,可以将其直接传递给onclick变量。

<form>
<p id="passError">ddd</p>
<button id="submit">Login</button>
</form>

<script type="text/javascript">
document.getElementById("submit").onclick = changeit;
function changeit(event)
{
    event.preventDefault();
    pError = document.getElementById("passError");
    pError.innerHTML = "wrong password";
}
</script>

07-28 10:11