我有一个包含多个文本输入的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)
gen*_*sis 10
单击"清除"按钮时,只有元素聚焦是"清除"按钮.你必须解决它.(触发onblur事件)
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更好的方法是在按钮即将获得焦点时存储对的引用。然而,要在所有浏览器中很好地实现这一点有点棘手。
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='';
| 归档时间: |
|
| 查看次数: |
19643 次 |
| 最近记录: |