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

How to prevent Enter causing Dojo website to reload

我有一个 Dojo 对话框,其中有一个表单、文本框和按钮。

当表单打开并且我在文本框中键入内容并按 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();
})   

查看下面的工作片段:

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",
        required:true,
        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>