如何防止 Enter 导致 Dojo 网站重新加载

问题描述

我有一个 Dojo Dialog,里面有一个 Form、TextBox 和 Button。

当表单打开并且我在 TextBox 中输入一些内容并按 Enter 时,整个网站会重新加载。

我怎样才能防止这种情况发生?单击“确定”按钮按预期工作。有没有办法禁用 Enter 行为?

var form = new Form();

new TextBox({
    placeHolder: "enter value:"
}).placeAt(form.containerNode);

new Button({
    label: "OK",'onClick': function () {
        console.log(`form value is: ${form._descendants[0].value}`)
        dia.hide();
    },}).placeAt(form.containerNode);

var dia = new Dialog({
    content: form,title: "Save",style: "width: 300px",});

form.startup();
dia.show();

解决方法

默认情况下,当我们点击回车时表单会提交,为了防止这种情况,您必须监听提交事件并使用 event.preventDefault()

添加上述代码将解决您的问题:

form.on("submit",function(e){
    e.preventDefault();
})   

参见 belwo 工作片段:

require(["dijit/Dialog","dijit/registry","dojo/ready","dijit/form/Button","dijit/form/Form","dijit/form/ValidationTextBox"],function(Dialog,registry,ready,Button,Form,ValidationTextBox) {


    ready(function() {
      
      
    
      var form = new Form();

      new ValidationTextBox({
        name:"textValue",required:true,placeHolder: "enter value:"
      }).placeAt(form.containerNode);

      new ValidationTextBox({
        name:"otherTextValue",placeHolder: "enter value:"
      }).placeAt(form.containerNode);

      new Button({
        label: "OK",type:"submit"
      }).placeAt(form.containerNode);

      var dia = new Dialog({
        content: form,title: "Save",style: "width: 300px",});
     
      form.on("submit",function(e){
         e.preventDefault();
         if(form.validate()) {
            console.log(form.get("value"))
            dia.hide()
         }
      })    
      
      form.startup();
      dia.show();
      
      
      
      registry.byId("btn").on("click",function() {
        form.reset();
        dia.show();
      });

    });
  }
);
<script type="text/javascript">
  dojoConfig = {
    isDebug: true,async: true,parseOnLoad: true
  }
</script>

<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>
<link href="//ajax.googleapis.com/ajax/libs/dojo/1.8.3/dijit/themes/claro/claro.css" rel="stylesheet" />

<body class="claro">
  <div data-dojo-type="dijit/form/Button" id="btn"> show again </div>
</body>

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...