如何在jquery中检查div是否有焦点?

问题描述:

我正在尝试在视图中使用kendo网格,我想在按Enter键后在网格中创建新行。我可以通过编写以下代码来做到这一点:

I'm trying to use kendo grid in my view, I want to create new row in the grid after pressing enter key. I can do this by writing following code:

<div id="GridContainer">
<div id="grid"></div>
</div>

$(document.body).keypress(function (e) {
    if (e.keyCode == 13) {
        var grid = $("#grid").data("kendoGrid");
        grid.addRow();
}
});

问题是,在页面上,无论何时按Enter键,它都会创建新行。但我希望只有当网格聚焦时才会这样。我怎样才能做到这一点?我试图将焦点应用于包含网格的div,但没有运气。为了便于阅读,我跳过了代码来生成kendo网格。谢谢。

The problem is, on the page, whenever I press enter, its creating new row. But I want that only when the grid is focused. How can I do that? I tried to apply focus to the div, that contains the grid, but no luck. I skipped the code to generate the kendo grid for readability. Thanks.

试试这个,

HTML

<div id="grid" tabindex="0"></div>

<div id="grid" contenteditable="true"></div>

SCRIPT

$(document.body).keypress(function (e) {
    if (e.keyCode == 13 && $("#grid").is(':focus')) {
        var grid = $("#grid").data("kendoGrid");
        grid.addRow();
    }
});

阅读如何将键盘焦点提供给DIV并将键盘事件处理程序附加到它?

Jquery .focus( )没有div的tabindex属性就无法工作

已更新

在添加之后再次聚焦 div ,例如,

Focus the div again after adding a row, like,

$(document.body).keypress(function (e) {
    if (e.keyCode == 13 && $("#grid").is(':focus')) {
        var grid = $("#grid").data("kendoGrid");
        grid.addRow();
        $("#grid").focus();
    }
});