2013-07-12 116 views
3

我正在做jQuery移动中的移动应用程序。当第一页加载时,它有一个init函数。我的要求是,当加载第一页时,光标应该指向文本框。我想:如何在页面上的文本框中设置光标init

$('#txtdemo').focus(); 

var txtBox=document.getElementById("txtdemo"); 
    txtBox.focus(); 

但两者都没有工作。请让我知道一个很好的方法来做到这一点。

+0

你有没有尝试将.focus调用放在一个setTimeout的时间说,200? – Jeff

+0

@vinithasreevijay,我认为你不能这样做,因为它可能像输入字段'txtdemo'可能不可用在初始化函数 –

+0

当我给焦点()文本框选择,但问题是,光标未指向文本框 –

回答

4

在手机网站,这是不可能使用编程文本框和键盘开放重点。这是一种可用性问题。在桌面版网站,你可以这样做

$('#txtdemo').focus(); 

$('#txtdemo').select(); 

$('#txtdemo').trigger('focus'); 

$('#txtdemo').trigger('click'); 
+0

谢谢迪文......它适用于我 –

+0

@vinit hasreevijay - 你的欢迎 –

3

它只能在pageshow事件中完成。它必须是pageshow因为网页只在该点完全形成。如果你不知道什么pageshow是看看我的文章关于jQuery Mobile页面事件。此外,这只适用于桌面浏览器,它不适用于移动浏览器。在移动浏览器的情况下,输入字段将处于焦点之下,但这不会触发键盘显示。

$(document).on('pageshow', '#index', function(){ 
    $('#some-input').focus(); 
}); 

工作例如:

<!DOCTYPE html> 
<html>http://jsfiddle.net/Gajotres/PMrDn/#update 
    <head> 
     <title>jQM Complex Demo</title> 
     <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/> 
     <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no; target-densityDpi=device-dpi"/> 
     <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" /> 
     <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> 
     <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script> 
     <script> 
      $(document).on('pageshow', '#index', function(){ 
       $('#some-input').focus(); 
      }); 
     </script>  
    </head> 
    <body> 
     <div data-role="page" id="index"> 
      <div data-theme="b" data-role="header"> 
       <h1>Index page</h1> 
      </div> 

      <div data-role="content"> 
       <input type="text" value="" id="some-input"/> 
      </div> 
     </div>  
    </body> 
</html> 
+0

这里也没有指向文本框 –

+0

你使用的是什么浏览器?我的例子已经在Firefox,Chrome和IE9上测试过了,它可以在所有的浏览器上运行 – Gajotres

+0

Chrome ..但它不适用于我 –

相关问题