【问题标题】:How do I automatically select text in a Backgrid cell when it receives focus?获得焦点时如何自动选择 Backgrid 单元格中的文本?
【发布时间】:2013-09-21 03:47:50
【问题描述】:

我有一个应用程序正在使用BackgridJS 作为类似电子表格的编辑器界面。当用户在一行中使用选项卡时,每个单元格 (Backgrid.StringCell) 都会自动变为可编辑的。但是,光标位于单元格内容的末尾,要求用户在向单元格输入新数据之前退格到字符串的开头。

我希望在单元格获得焦点时自动突出显示单元格内容,以便用户可以立即开始在该单元格中输入新数据,或者通过 Tab 键转到下一个单元格以保留该数据。

我觉得我应该听 StringCell 的 enterEditMode 事件,但我不知道从那里去哪里。我目前有:

var stringCell = Backgrid.StringCell.extend({
    enterEditMode: function() {
        // highlight cell contents here
    }
});

【问题讨论】:

  • 尝试为你的模型添加一个监听器来处理 backgrid:editing 事件。我认为回调的第四个参数是对单元格可编辑时生成的输入字段的引用。您可能可以使用 jquery select 来选择字段中的文本。
  • @net.uk.sweet,你能给我举个例子吗?坦率地说,我对 Backgrid 或 Backbone 不是很熟悉,而且我现在真的没有时间学习它,我只需要这个快速的功能。

标签: jquery backbone.js backgrid


【解决方案1】:

从 BackgridJS 作者的正确方向,我能够想出这个解决方案:

var decimalFormatter = {
  fromRaw: function (rawData) {
    if(rawData == 0)
    {
      return '';
    }

    return rawData;
  },

  toRaw: function(data) {
    return data;
  }
};

/*
  Create a new custom cell type and set a custom formatter.
  Override the postRender() method in order to automatically select the 
  cell's contents for easier data entry when tabbing across rows.
*/

Backgrid.MyCell = Backgrid.StringCell.extend({
    className: "my-cell",
    formatter: decimalFormatter,
    editor: Backgrid.InputCellEditor.extend({
      postRender: function (model, column) {
        if (column == null || column.get("name") == this.column.get("name")) {
          // move the cursor to the end on firefox if text is right aligned
          if (this.$el.css("text-align") === "right") {
            var val = this.$el.val();
            this.$el.focus().val(null).val(val).select();
          }
          else {
            this.$el.focus().select();
          }
        }

        return this;
      }
    })
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-13
    • 2011-03-13
    • 2013-03-15
    • 2014-03-03
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多