1

I'd like to create an onfocus function to my input fields in a form. I'm working with a drag and drop landing page wizard(in Marketo) therefore I don't have access to the HTML tags.

I tried to do use getElementById and it worked only on the first field. I also tried the following:

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

    this.value=''


}

</script>
4

4 回答 4

2

您查询所有<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 = '';});
于 2013-01-27T08:30:06.753 回答
0

另一个变体是这个

    //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;
}
于 2013-01-27T08:32:23.207 回答
0

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

$("input").on("focus",function(){
    //function data block goes here    
});
于 2013-01-27T08:36:35.690 回答
0

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

$("input").on("focus",function()
{
    this.value=''  
});
于 2013-01-27T09:57:25.047 回答