问题
I'm trying to add autofocus to an input form when it's hovered.
Using the .appentTo attribute but open to other solutions.
Here's what I have:
<input value=""/>
$(document).ready(function(){
$("input").hover(function(){
$("autofocus").appendTo("input");
});
});
Fiddle: https://jsfiddle.net/t7yj3b4n/1/
回答1:
To focus an element use focus()
method. Here you try to add the attribute autofocus
with a bad method (take a look at Zakaria's answer) to all input. Use $(this)
for target the hovered element
Example
$(document).ready(function(){
$("input").hover(function(){
$(this).focus();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input value=""/><input value=""/><input value=""/>
回答2:
To add attribute to element you should use .attr()
or .prop()
and not appendTo
:
$(document).ready(function(){
$("input").hover(function(){
$(this).prop('autofocus');
});
});
NOTE : The autofocus
attribute will not make the input focused but focus()
instead.
Hope this helps.
回答3:
$(document).ready(function(){
$("input").hover(function(){
$(this).focus();
});
});
https://jsfiddle.net/t7yj3b4n/2/
回答4:
You must use .focus();
$(document).ready(function(){
$("input").hover(function(){
$(this).focus();
});
});
来源:https://stackoverflow.com/questions/41015515/adding-autofocus-attribute-when-input-is-hovered