如何在jquery中检查div是否有焦点? [英] how to check whether a div is focused or not in jquery?

查看:91
本文介绍了如何在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();
    }
});

这篇关于如何在jquery中检查div是否有焦点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆