jQuery 不使用键盘导航选择文本

jQuery not selecting text with keyboard navigation

我有一张成绩单,其中显示了许多学生的许多分数。当教师浏览 table 时,程序应 select 字段中的文本,以便教师可以更改分数而不必删除之前的值。

这是我当前的咖啡脚本:

$("input:text").focus ->
    $(this).select()

if $('#scoreTable').length > 0
    document.getElementById("r0c0").focus()

    $(".some_cell").keydown (e) ->
        if e.which == 38
            next_row = parseInt($(this).attr("cell_row")) - 1
            next_col = parseInt($(this).attr("cell_col"))

        else if e.which == 40
            next_row = parseInt($(this).attr("cell_row")) + 1
            next_col = parseInt($(this).attr("cell_col"))

        else if e.which == 37
            next_row = parseInt($(this).attr("cell_row"))
            next_col = parseInt($(this).attr("cell_col")) - 1

        else if e.which == 39
            next_row = parseInt($(this).attr("cell_row"))
            next_col = parseInt($(this).attr("cell_col")) + 1

        $("#r"+next_row+"c"+next_col).focus()

初始 select 命令在页面加载时正常工作。但是当我使用箭头键跳转到另一个单元格时,光标位于文本之后。什么都没有 selected。

这里嵌入的 ruby html 创建了 table:

<div>
    <table class="table-borderless scoreTable" id="scoreTable">
      <thead class="table-borderless">
        <th class="table-borderless">Student</th>
        <% @objectives.each_with_index do |objective, index| %>
          <th class="rotate table-borderless"><div><span>
            <%= link_to objective.short_name, edit_objective_path(objective) %>
          </span></div></th>
        <% end %>
      </thead>
      <tbody>
        <% @students.each_with_index do |student, indexx| %>
          <tr>
            <td><h4><%= link_to student.last_name_first, edit_teaching_requests_student_url(student) %> </h4></td>
            <% this_ss = student.seminar_students.find_by(:seminar_id => @seminar.id) %>
            <% @objectives.each_with_index do |objective, indexy| %>
              <% this_score = @scores.find_by(:objective => objective, :user => student) %>
              <td class="themScores to_unhide score_cell">
                <% if this_score %>
                  <%= text_field "scores[#{this_score.id}]", "", :class => "some_cell", :value => this_score.points,
                    :id => "r#{indexx}c#{indexy}", :cell_row => indexx, :cell_col => indexy %>
                <% end %>
              </td>
            <% end %>
          </tr>
        <% end %>
      </tbody>
    </table>
  </div>

我试过将这一行添加到 coffeescript 中:

$("#r"+next_row+"c"+next_col).select()

我已经尝试采纳这个问题 Looking for a better workaround to Chrome select on focus bug 的建议,我认为它会像这样转化为 coffeescript:

$("#r"+next_row+"c"+next_col).select().mouseup (e) ->
    e.preventDefault()
    $(this).unbind("mouseup")

提前感谢您的任何见解。

我在继续浏览其他问题时发现了这个片段。它完成了工作。

        $("#r"+next_row+"c"+next_col).focus()
        callback = -> 
            $("#r"+next_row+"c"+next_col).select()
        setTimeout callback, 10

归功于 how to write setTimeout with params by Coffeescript