【问题标题】:Prevent page reload on form Button click in meteor?防止页面重新加载表单按钮点击流星?
【发布时间】:2012-11-24 01:22:04
【问题描述】:

不确定这是 Meteor 问题、JavaScript 问题还是其他问题。单击表单按钮会导致不需要的页面重新加载。

其他信息:

  • 使用引导包
  • 使用jQuery包
  • 使用主干包
  • 即使删除了上述软件包,仍然会出现页面重新加载问题
  • 注释掉 Posts.insert() 行也不能解决问题

    // 来自 application.js
    // *这是应用程序中唯一与事件相关的代码(除了流星从我们那里抽象出来的任何幕后内容

    Template.new_post.events = { 
    
        'click #submit' : function () {
    
          var text = $('#title').val();
          var cat = $('#category').val();
    
          // save our post with the value of the textbox
          Posts.insert({title : text, category : cat});
        }
    };
    

    // 来自 index.html

    <template name="new_post">
      <form class="form-horizontal">
        <fieldset>
        <div class="control-group">
          <!-- Text input-->
          <label class="control-label" for="title">Title</label>
          <div class="controls">
            <input type="text" id="title" value="{{text}}" class="input-xlarge">
            <p class="help-block">Hint: Summarize your post in a few words</p>
          </div>
        </div>
        <div id="form-part-2">
          <div class="control-group">
            <label class="control-label" for="categories">Category</label>
            <div class="controls">
              <select class="input-xlarge" id="category">
                {{#each categories}}
                  <option value="{{defaultLabel}}">{{defaultLabel}}</option>
                {{/each}}
              </select>
              <p class="help-block">Hint: Choose a category</p>
            </div>
          </div>
            <!-- Button -->
            <div class="control-group">
              <div class="controls">
                <button class="btn btn-success" id="submit">Done</button>
              </div>
            </div>
        </div><!-- end div form-part-2 -->
        </fieldset>
      </form>
    </template>
    

【问题讨论】:

    标签: javascript html http meteor


    【解决方案1】:

    我认为您必须在函数结束时返回 false 以防止提交。

    【讨论】:

    • 我也遇到了这个问题。谢谢!
    • return false 在 Firefox 33 的 Meteor 1.0 中似乎对我不起作用。
    • 不,您不应该使用 return false。你应该总是使用event.preventDefault();
    【解决方案2】:

    除了返回false,您还可以在event passed into your handler 上拨打preventDefault()

    'click #submit' : function (template, event) {
      ...
      event.preventDefault();
    }
    

    这只会阻止默认操作(即提交表单),但不会阻止事件传播。

    【讨论】:

    • event.preventDefault() 在 firefox 上不起作用 stackoverflow.com/q/18464913/522050
    • 如果这个方法适合你,你可以把它放在开头,这样以后的任何错误都不会导致页面刷新。
    猜你喜欢
    • 2021-03-01
    • 2012-12-09
    • 2019-06-24
    • 2019-04-12
    • 2012-03-21
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    相关资源
    最近更新 更多