这是我的 HTML 代码:
document.getElementById("sub").addEventListener("click", testing());
function testing() {
document.getElementById("demo").innerHTML ="good";
}
<input type="submit" value="Place Order" id="sub"/>
</fieldset> </form>
<p id="demo"></p>
<script type="text/javascript" src="Q4.js"></script>
我在其中声明了一个提交表单的按钮。
我向提交按钮添加了一个事件以运行函数 testing()
。
我预计当用户点击提交按钮时,页面会提示“good”。但是,一旦我加载页面,“good”就已经出现,而无需单击按钮。
result page
为什么会这样?
您应该删除括号以防止函数 testing()
被执行。只需输入函数名称即可。
您可以找到更多详细信息和简单的example of listener here .
这是一个工作片段:
/*file javaScript Q4.js*/
document.getElementById("sub").addEventListener("click", testing);
function testing() {
document.getElementById("demo").innerHTML ="good"; }
<input type="submit" value="Place Order" id="sub"/>
</fieldset> </form>
<p id="demo"></p>
<script type="text/javascript" src="Q4.js"></script>
你也可以将你的函数直接放到你的监听器中,像这样:
document.getElementById("sub").addEventListener("click", function() {
document.getElementById("demo").innerHTML="good";
});
About the bug that "show the good
word for a second only" :
Clicking the button causes the form to be submitted, which means the page reloads or the loads the URL in action. That means that all
temporary changes that JavaScript made in the current page load are
gone. Thanks Felix Kling