如何在JavaScript中获得以前关注的元素?

Has*_*imR 14 html javascript

我有一个包含多个文本输入的HTML表单.我希望在按下"清除"按钮之前清除具有焦点的元素.如何在JavaScript中获取该元素?

注意:重新考虑将评论考虑在内.

lar*_*dev 14

创建一个全局变量来存储当前聚焦元素的id,

var cur_id;
Run Code Online (Sandbox Code Playgroud)

onblur每个元素调用一个函数并传递id

<input type="text" id="name" name="name" onBlur="setId(this.id)">
Run Code Online (Sandbox Code Playgroud)

并将id设置为该函数的全局变量

function setId(id) {
    cur_id = id;
}
Run Code Online (Sandbox Code Playgroud)

并编写一个用于onclick清除按钮的功能,就像这样

function clear() {
    document.getElementById(cur_id).value = "";
}
Run Code Online (Sandbox Code Playgroud)

  • @shesek:这是有效的并且没有任何伤害,并且在上下文中可能是合适的,所以我会说这是一个严厉的downvote. (4认同)

gen*_*sis 10

单击"清除"按钮时,只有元素聚焦是"清除"按钮.你必须解决它.(触发onb​​lur事件)

  • 哦悖论是悲剧......*呜咽呜咽* (2认同)
  • 我讨厌`focus`事件没有'justblurred`(或类似)属性的方式.它可能是"null",它不是特定的元素. (2认同)

Tim*_*own 9

document.activeElement最简单的方法是在按钮上的事件中存储对mousedown事件的引用,尽管这是一种以鼠标为中心的方法,并且不适用于来自键盘和其他设备的按钮“点击”。

现场演示: http: //jsfiddle.net/tEP6w/

代码:

var clearButton = document.getElementById("clear");
var previousActiveElement = null;

clearButton.onmousedown = function() {
    previousActiveElement = document.activeElement;
};

clearButton.onclick = function() {
    if (previousActiveElement && previousActiveElement != this) {
        previousActiveElement.value = "";
    }
};
Run Code Online (Sandbox Code Playgroud)

document.activeElement更好的方法是在按钮即将获得焦点时存储对的引用。然而,要在所有浏览器中很好地实现这一点有点棘手。


she*_*sek 7

var focused, inputs = document.getElementsByTagName('input');
for (var i=0, input; i<inputs.length && (input = inputs[i]); i++) {
    if (input.type === 'text') {
        input.addEventListener('focus', function(){
            focused = this;
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

或者在jQuery中: var focused; $('input:text').focus(function(){focused = this;});

当你想要清除焦点元素时, focused.value='';

  • 他没有"jQuery"标签;)但这不是我的downvote (2认同)