如何在按下输入时找到哪个输入字段被聚焦? (jquery的)

时间:2015-03-19 22:57:24

标签: jquery

我的表单中有3个输入字段(textfield)。

<input id="input1" name="input1" type="text" value="">
<input id="input2" name="input2" type="text" value="">
<input id="input3" name="input3" type="text" value="">

我也有这条javascript:

$("#timetable").on("submit", function(event) {
    console.log("input " + $("input").attr("id") + "has focus");
});

我想知道按下输入/返回按钮时哪个输入字段有焦点。我在网上搜索过但是空了。

由于

1 个答案:

答案 0 :(得分:3)

  

MDN - Document.activeElement

     

Document.activeElement返回当前关注的元素,即用户输入任意键时将获得击键事件的元素。该属性是只读的。

因此,在提交事件监听器中,您将访问document.activeElement,这是焦点元素。

Example Here

$("#timetable").on("submit", function (event) {
    console.log(document.activeElement);    // element
    console.log(document.activeElement.id); // element id

    $(document.activeElement).css('border-color', 'red');
});
相关问题