how to check whether a div is focused or not in jquery?

谁说胖子不能爱 提交于 2019-12-11 03:04:51

问题


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


来源:https://stackoverflow.com/questions/17564315/how-to-check-whether-a-div-is-focused-or-not-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!