专注于第一个表单元素,无论它是什么.j查询对话框

Focus on first form element, whatever it may be. jQuery dialog

本文关键字:它是什么 查询 对话框 第一个 表单 元素 专注      更新时间:2023-09-26

>我有一个jQuery模式对话框,当它打开时,我希望它专注于第一个表单元素。

目前我有这个:

the_dialog.dialog({ 
        modal: true, 
        width: 700,
        title: 'title',
        close: suicide ,
        open: function(event, ui) { 
                setTimeout(function() {
                    jQuery('#').focus(); <-- VERY SPECIFIC CSS SELECTOR PERHAPS?
                }, 220);     
            } 
    }
);
我的

问题是这个对话框是从我的应用程序中的几个不同位置调用的,第一个表单元素有时可以是input,有时可以是select

表单

的布局始终相同,只有第一个表单元素可能会发生变化。

<table>
    <tbody>
        <tr>
            <td>LABEL</td>
            <td>FIRST FORM ELEMENT</td>
        </tr>
        <tr>
            <td>LABEL</td>
            <td></td>
        </tr>
        <tr>
            <td>LABEL</td>
            <td></td>
        </tr>
        <tr>
            <td>LABEL</td>
            <td></td>
        </tr>
    </tbody>
</table>

在不添加任何类或 ID 的情况下,当表单打开时,我可以专注于第一个表单元素,无论它是什么?

可以在打开的回调中使用伪:input选择器并查找第一个非隐藏元素

open: function(event, ui) { 
       the_dialog.find(':input:not(:hidden):first').focus()     
 }

:input过滤标签<input><textarea><select>

:hidden过滤任何在display:nonetype="hidden"中不可见的标签

你可以

试试

jQuery('input,select').first().focus();

关于注释,您应该将其范围限定为仅适用于对话框,例如

http://jsfiddle.net/chkfgfwy/

您可以使用:input选择器在对话框中查找第一个表单元素:

the_dialog.find(':input:first').focus()

我建议:

// I'm assuming that <textarea> elements may be used, they can be removed if not;
// 'dialog' is an assumed reference to a jQuery object containing the relevant <table>:
dialog.find('input, select, textarea')
  // retrieving the first element matched by the selector:
  .eq(0)
  // focusing that found element:
  .focus();

// this part is entirely irrelevant, and used only to vary the "first form element",
// in order to demonstrate the approach working, regardless of which element is 'first':
var formElements = ['<input />', '<select></select>', '<textarea></textarea>'];
$('td:nth-child(2)').html(function(i) {
  return $(formElements[Math.floor(Math.random() * formElements.length)]).val(i);
});
// the relevant part (explained above):
$('input, select, textarea').eq(0).focus();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr>
      <td>LABEL</td>
      <td></td>
    </tr>
    <tr>
      <td>LABEL</td>
      <td></td>
    </tr>
    <tr>
      <td>LABEL</td>
      <td></td>
    </tr>
    <tr>
      <td>LABEL</td>
      <td></td>
    </tr>
  </tbody>
</table>

引用:

  • JavaScript:
    • Math.random() .
    • Math.floor .
  • j查询:
    • eq() .
    • focus() .
    • html() .

我们可以<th>标签来包装您的标签吗?

然后你可以使用

$('table').find('td').eq(0).children().eq(0).focus()

虽然它有点冗长,但如果孩子是输入、选择或其他任何东西(文本区域等)会起作用