【问题标题】:Button's function always called when enter key is pressed at text input element在文本输入元素处按下回车键时始终调用按钮的函数
【发布时间】:2015-08-24 21:53:09
【问题描述】:

此代码表示一个 html 标记,用户可以在其中将一部或多部手机添加到她/他的个人资料中。因此,我使用主干添加用户可以指定的文本字段。

<form method="post" class="form-horizontal" action="..">

   <!-- Here I have another text input controls -->

    <!-- START: backbone view -->
    <div id="phones">
        <div class="phones-container">
            <!-- New phone template [label, text input] -->      
        </div>

        <!-- Add phone template button -->
        <button id="btn-add-phone">Add another phone</button>
    </div>
    <!-- END: backbone view -->
</form>

电话模板如下所示:

<div class="form-group tpl-phone">
    <label class="">Other:</label>
    <div class="col-sm-8 col-lg-7 controls">
        <input value="" type="tel" class="reference" name="reference[]" >
    </div>
</div>

在主干中,我有一个向视图添加新电话模板的功能。

请注意...主干视图只是表单的一部分。

var PhoneEditorView = Backbone.View.extend({
    el: '#phones',
    events: {
        "click #btn-add-phone": "onAddPhoneTemplate",
        "keyup .reference": "onTypingReference"
    },

    initialize: function (options) {
        _.bindAll(this, 'onAddPhoneTemplate', 'onTypingReference', 'render');
        this.model = new PhoneEditor(options);
        this.render();
    },

    onAddPhoneTemplate: function(event){
        event && event.preventDefault(); //prevents submit form 
        console.log('onAddPhoneTemplate()');
        var $template = $('.tpl-phone').clone().removeClass('tpl-phone');

        $('.phones-container').append($template);
    }, 

    onTypingReference: function(event){
        event && event.preventDefault(); 
        if(event.which == 13){
            console.log('enter key');
        }
    },

    render: function(){
    }
});  

有什么问题?如果用户在任何文本字段上按 Enter 键,无论它是在视图范围内还是在视图范围之外,出于某种原因onAddPhoneTemplate() 函数再次调用并将另一个电话的模板添加到视图中。

  • 输入键的预期行为是什么都不做,控制台的输出:

    enter key
    
  • 但是,按回车键后,我进入控制台:

    onAddPhoneTemplate()
    enter key
    

【问题讨论】:

标签: javascript jquery html backbone.js


【解决方案1】:

将您的按钮更改为type=button

除非另有说明,否则默认情况下按钮为type=submit,因此当放置在表单中时,它将触发表单提交。

当表单中存在type=submit时,点击enter也会触发表单提交

<button type="button" id="btn-add-phone">Add another phone</button>

【讨论】:

  • 我从没想过问题出在那儿。我扫描了我的主干代码至少 1 个一小时。非常感谢,祝你有美好的一天
  • 没问题...我知道这条规则,但有时还是会因为自己搞砸了它而扇自己耳光
猜你喜欢
  • 2015-08-22
  • 2014-01-26
  • 2014-05-30
  • 2010-11-13
  • 2015-02-17
  • 1970-01-01
  • 2011-04-10
  • 2013-02-04
  • 1970-01-01
相关资源
最近更新 更多