仅将焦点事件绑定到子元素

Bind focus event to children elements only

本文关键字:元素 绑定 事件 焦点      更新时间:2023-09-26

我想只将focus()事件绑定到具有特定类的div的子级。这是我尝试过的,但没有奏效:

var boxedElements = "p,div,h1,h2,h3,h4,h5,h6,table";
    $(".myBox").find(boxedElements).focus(function () {
        var tagname = $(this).prop("tagName");
        console.log(tagname);
    });

由于某种原因,该功能从未达到。关于如何处理这个问题的任何想法?

编辑

<div class="myBox" contenteditable="true">
<h3>This is a header</h3>
<p>This is a paragraph</p>
<p>This is another paragraph</p>
</div>

现在,用户可以单击元素,或者,由于其内容可编辑,可以使用键盘箭头从h3导航到第一个p元素。我希望能够检测到这一点。

这就是我最终解决它的方式,感谢@Nikolay Ermakov 和 @mmativ

    var boxedElements = "p,div,h1,h2,h3,h4,h5,h6,table";
    $(".myBox").find(boxedElements).click(function (e) {
        var tagname = $(this).prop("tagName");
        console.log(tagname);
        e.stopPropagation();
    });
    $(".shmeditor").click(function () {
        var tagname = $(this).prop("tagName");
        console.log("other tag: " + tagname);
    });
    $(".myBox").keydown(function (e) {
        var $element = $(getSelection().getRangeAt(0).commonAncestorContainer.parentNode).closest(boxedElements);
        if ($element.hasClass("myBox")) {
            console.log("other tag: ");
        }
        else {
            console.log($element.prop("tagName"));
        }
    });