【问题标题】:Knockout event binding for input keypress causes weird behavior输入按键的敲除事件绑定导致奇怪的行为
【发布时间】:2023-03-30 23:31:01
【问题描述】:

长话短说,我想让用户在输入元素上按回车键,然后调用我的视图模型中的某些方法。这是我的 html 输入:

<input id="searchBox" class="input-xxlarge" type="text" data-bind="value: searchText, valueUpdate: 'afterkeydown', event: { keypress: $parent.searchKeyboardCmd}">

这是我在 vm 中的方法:

searchKeyboardCmd = function (data, event) { if (event.keyCode == 13) searchCmd(); };

一切正常,searchCmd 在我输入输入时被调用,但问题是我无法在输入中输入任何内容,即我在输入中输入的所有内容都被忽略。提前感谢您的帮助。

【问题讨论】:

    标签: mvvm knockout.js dom-events keypress html-input


    【解决方案1】:

    根据 KO 文档,如果要继续执行默认操作,则必须从事件处理程序中返回 true

    searchKeyboardCmd = function (data, event) {
        if (event.keyCode == 13) searchCmd();
        return true;
    };
    

    【讨论】:

    • 好吧,非常感谢 f_martinez!它现在完美运行,虽然我不明白为什么这是必要的!
    【解决方案2】:

    here's 一个小提琴,它演示了你试图做什么,并用 keyup 替换你的代码中的事件'keypress',并删除 $parent 只包含函数名称,除非文本字段在一个淘汰赛 foreach 循环内。这是下面修改代码

    <input id="searchBox" class="input-xxlarge" type="text" data-bind="value: searchText, valueUpdate: 'afterkeydown', event: { keyup: searchKeyboardCmd}"
    

    【讨论】:

    • 这是对我有帮助的答案,因为它不依赖于 enter 或 keycode==13
    【解决方案3】:

    这是一个工作示例。

    http://jsfiddle.net/tlarson/qG6yv/

    <!-- ko with: stuff -->
      <input id="searchBox" class="input-xxlarge" type="text" 
        data-bind="value: searchText, valueUpdate: 'afterkeydown', 
        event: { keypress: $parent.searchKeyboardCmd}">   
    <!-- /ko -->
    

    还有 javascript:

    var stuffvm = function(){
        var self = this;
    
        self.searchText = ko.observable();
    };
    
    var vm = function() {
        var self = this;
    
        self.stuff = new stuffvm();
    
        self.searchCmd = function() {
            console.log("search triggered");
        };
    
        self.searchKeyboardCmd = function (data, event) { 
            if (event.keyCode == 13) {
                self.searchCmd(); 
            }
            return true;
        }
    }
    
    ko.applyBindings(new vm());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-16
      • 1970-01-01
      • 2015-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多