如何通过HTML表单单次提交触发JS类多个方法顺序执行
问题原因
你的代码失效有两个直接原因:
- HTML标签不支持重复定义同名属性,你在form标签上写了两个
onclick,浏览器只会识别第一个,第二个会被直接丢弃。 - 表单内的submit按钮点击后默认会触发页面提交跳转,页面刷新会导致控制台的输出被清空,就算事件绑定正确也看不到结果。
另外你当前类里的printArea方法本身已经内置了calcArea的调用,如果没有特殊要求,只调用printArea就可以得到计算结果,如果你需要显式按顺序先单独执行一次calcArea再执行printArea,按下面的方案修改即可。
解决方案
方案1:修正内联事件绑定
把两个方法调用放到同一个onclick属性中,同时阻止表单默认提交行为,修改后form标签代码如下:
<form id="nameForm" onclick="square.calcArea(); square.printArea(); return false;"> <input type="submit" value="print area in console" id="btn"> </form>
其余代码保持不变,点击按钮后控制台就会正确输出100。
方案2:规范写法(推荐)
不建议在HTML标签上写内联事件,把结构和逻辑分离更易维护,完整代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Form</title> </head> <body> <form id="nameForm"> <input type="submit" value="print area in console" id="btn"> </form> <script> class Rectangle { constructor(height, width) { this.height = height; this.width = width; } printArea() { console.log(this.calcArea()); } calcArea() { return this.height * this.width; } } const square = new Rectangle(10, 10); const form = document.getElementById('nameForm'); form.addEventListener('submit', function(e) { e.preventDefault(); square.calcArea(); square.printArea(); }) </script> </body> </html>
这种写法通过addEventListener绑定submit事件,用e.preventDefault()阻止表单默认跳转,执行顺序完全可控,也不会出现HTML属性重复定义的问题。
内容的提问来源于stack exchange,提问作者asker
相关产品推荐
相关产品推荐

