html onload字段焦点问题

时间:2011-03-09 10:52:09

标签: html

我使用以下html代码在页面加载时聚焦输入字段,为什么它不起作用?

<input class="myinput" id="the_username" onLoad="$('#the_username').focus()" size="30" type="text" /> 

我想在html中按照上面的方式进行操作

3 个答案:

答案 0 :(得分:2)

因为onLoad XHTML属性can be bound only<body><frameset>标记。

所以把它放在你的<body>标签上,或者最好(因为HTML中的Javascript内联很可怕)在适当的Javascript / jQuery中设置onLoad处理程序:

$(function() {
   $('#the_username').focus();
});

答案 1 :(得分:0)

将其放入HTML

$(document).ready(function(){
    $('#the_username').focus();
})

我不确定输入是否会触发onLoad

答案 2 :(得分:0)

只需使用'HTML5'autofocus属性:

<input class="myinput" id="the_username" type="text" autofocus>

这适用于Firefox 4和最新的稳定Opera,Chrome和Safari。

对于不支持autofocus的浏览器,可以轻松编写回退,尤其是在这种情况下使用jQuery时。

$(function() {
  if (!('autofocus' in document.createElement('input'))) {
    $('#the_username').focus();
  }
});