如何将对焦功能应用于所有“输入”对象

How to apply onfocus function to all "input" objects?

本文关键字:输入 对象 应用于 功能      更新时间:2023-09-26

我想在表单中为我的输入字段创建一个onfocus函数。我正在使用拖放登录页面向导(在 Marketo 中),因此我无法访问 HTML 标签。

我尝试使用 getElementById,它仅适用于第一个字段。我还尝试了以下方法:

<script>
var input = document.getElementsByTagName('input')[0]
input.onfocus = function() {
    this.value=''

}
</script>

查询所有<input> s 元素,但仅使用第一个匹配项:

var input = document.getElementsByTagName('input')[0]

遍历所有比赛并施展你的魔术:

var inputs = document.getElementsByTagName('input');
for (var i=0; i< inputs.length; i++){
    inputs[i].onfocus = function(){this.value = '';};
}

如果你可以使用jQuery,那就容易多了:

$('input').focus(function(){this.value = '';});

另一个变体是这个

    //get all inputs
var inputs = document.getElementsByTagName('input')
    //cache the length
  , inputsLen = inputs.length;
//define one handler
function focusHandler(){
  this.style.backgroundColor = 'red';
}
//loop through all
while(inputsLen--){
  //each element's onfocus references only one function instead of "one each"
  inputs[inputsLen].onfocus = focusHandler;
}

是的,在jquery中你可以这样做:

$("input").on("focus",function(){
    //function data block goes here    
});

每个人都打败了我,但试试这个

$("input").on("focus",function()
{
    this.value=''  
});