jQuery set var其中n是tabindex顺序的ID?

时间:2012-04-15 15:13:44

标签: jquery

如何将下面的两个脚本合并为一个,目标是让脚本为表单中的输入/选择字段生成tabindex顺序功能(其中1,7,3是字段的ID(#)) ?

$(function(){
var tabindex = 1;
$('input,select').each(function() {
    if (this.type != "hidden") {
        var $input = $(this);
        $input.attr("tabindex", tabindex);
        tabindex++;
    }
});
});


$(function () {
var tab_order_positions = [1, 7, 3],
tab_order = 0;
for (var i = 0, _len = tab_order_positions.length; i < _len; i++) {
    $('#input_' + tab_order_positions[i]).attr('tabindex', ++tab_order);
}
});

1 个答案:

答案 0 :(得分:0)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var tab_order_positions = ['1', '7', '3']
            var tabindex = tab_order_positions.length;

            $.each(tab_order_positions, function (i, tab_order_position) {
                $('#input_' + tab_order_position).attr('tabindex', i);
            });

            $('input, select').each(function (i) {
                var obj = $(this);

                if (obj.attr('type') != 'hidden' && (obj.attr('id') !== undefined && $.inArray(obj.attr('id').split('_')[1], tab_order_positions)) === false) {
                    obj.attr('tabindex', tabindex);
                    tabindex++;
                }
            });
        });
    </script>
</head>
<body>
    Name:<input type="text" id="input_1" /><br />
    <input type="hidden" /><br />
    <input type="hidden" /><br />
    Age:
    <input type="text" id="input_3" /><br />
    Birth:
    <input type="text" /><br />
    Test:<select>
        <option>a</option>
        <option>b</option>
    </select><br />
    Gender:
    <input type="radio" name="gender" />
    Male
    <input type="radio" name="gender" />Female
    <br />
    Vechical:
    <input type="checkbox" name="Vechical" /><br />
    <input type="checkbox" name="Vechical" /><br />
    <input type="checkbox" name="Vechical" /><br />
    <input type="hidden" />
    test1:
    <input type="text" id="input_7" /><br />
    test2:
    <input type="text" /><br />
    test3:
    <input type="text" /><br />
    test4:
    <input type="text" /><br />
</body>
</html>