当页面加载时,JQuery将聚焦于第一个文本框或文本区域。

6

我试图编写一个jQuery,使页面加载时聚焦于第二个表单中第一个可见且启用的文本框或文本域。在下面的示例中,聚焦于form2中的输入text2

jQuery动态聚焦于第一个输入框或文本域提出的解决方案对我不起作用。

请注意,我们的应用程序中有多个页面。在某些页面上,表单的第一个字段是文本框,在其他页面上,第一个字段是文本域。我想编写一个jQuery方法,它将适用于所有页面,无论第一个字段是文本框还是文本域。在下面的示例中,如果我们交换textarea1text2字段,则解决方案应该适用。

<div id="header">
  <form name="form1">
    <input type="text" name="text1">
  </form>
</div>
<div id="content">
  <form name="form2">
    <input type="checkbox" name="chc" value="test"><br>
    <input type="hidden" name="hide">
    <input type="text" name="text2"><br>
    <textarea name="textarea1"></textarea><br>
    <input type="text" name="text3">
  </form>
</div>

这是我迄今为止尝试过的内容...

// throws the error - $("#content input:text, #content textarea").first is not a function
$("#content input:text, #content textarea").first().focus();

// focuses on the textarea even if a text box is the first element in the form
$("#content textarea, #content[type='text']:visible:enabled:first").focus();

// focuses on the last text box in the page!
$("#content :input[type='text'], :textarea:visible:enabled:first").focus();

// focuses on the first text box even if a textarea is the first element in the form
$("#content :input[type='text']:visible:enabled:first, :textarea:visible:enabled:first").focus();

// focuses on the checkbox as it is the first input element
$('#content :input:visible:enabled:first').focus();

谢谢。

6个回答

9
$("#content input:text, #content textarea").eq(0).focus()

3
这里是你需要的:
​$(function(){
  $('form[name=form2]').find(':text, textarea').filter(":visible:enabled").first().focus();
})​

一个例子 这里


嗨,Rafael,谢谢,这个可以用,但是我无法引用表单名称,因为每个页面的表单名称都不同。div id“content”在所有页面中都是相同的。是否可以使用div id而不是表单名称? - neo108
当然,@neo108...容器的选择器可以是任何一个丢弃第一个表单的人,所以$('#content')可以使用:] - Rafael Verger

1
<script type="text/javascript">
$(document).ready(function() {
    // focus on the first visible and enabled input field or textarea
    $(":input:visible:enabled").each(function() {
        if (($(this).attr('type') == 'text') && ($(this).is('input'))){
            $(this).focus();
            return false; 
        }
        if ($(this).is('textarea')){
            $(this).focus();
            return false; 
        }       
    });
});
</script>

1
如果您使用Raphael Verger的解决方案,它也可以是一个密码,因此:
​$(function(){
  $('form[name=form2]').find(':text, textarea, :password').filter(":visible:enabled").first().focus();
})​

0
你应该使用 DOM 元素而不是 jQuery 对象,像这样:
$("#content input:text")[0].focus()

0

// 抛出错误 - $("#content input:text, #content textarea").first 不是一个函数 $("#content input:text, #content textarea").first().focus();

这应该可以正常工作。请检查您的 JQuery 版本,first method 是在 JQuery 1.4 中添加的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接