how to check whether a div is focused or not in jq

2019-07-19 02:29发布

问题:

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();
}
});

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.

回答1:

Try this,

HTML

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

or

<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();
    }
});

Read How can I give keyboard focus to a DIV and attach keyboard event handlers to it? And Jquery .focus() not working without tabindex attribute of div

Updated

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();
    }
});