Adding autofocus attribute when input is hovered

北城余情 提交于 2021-02-11 07:37:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!