如何将焦点转移到select2中的下一个元素

问题描述 投票:1回答:3

我想在select2中选择更改时将焦点移到下一个元素上。但我不能这样做。为什么我的重点不转移到下一个领域?

HTML代码

<form>
<select autofocus id="select2" name="entry_id">
    <option value="0">00000000</option>
    <option value="1">11111111</option>
</select>
<input type="text" name="entry_id2" class="entry2">

javascript代码

$("#select2").select2();
$("#select2").on("change", function () {
 $(this).closet("form").find(".entry2").focus();
});

样本页面:https://jsfiddle.net/39wk54zk/

jquery-select2-4
3个回答
0
投票

这可能不是100%修复,但我注意到在这段代码中,你已经写了.closet而不是.closest:

 $(this).closet("form").find(".entry2").focus();

我认为它应该是:

 $(this).closest("form").find(".entry2").focus();

我没有测试过,但这可能是你问题的一部分。


0
投票

这是向后或向前移动焦点的完整代码。

      let cursorDirection = ''
    $(document).keydown(function (e) {
        let key = e.which || e.keyCode;
        if (e.shiftKey) {
            //does not matter if user has pressed tab key or not
            cursorDirection = 'prev';
        }
        else if (key == 9) {
            //if tab key is pressed then move next.
            cursorDirection = 'next';
        }
        else {
            cursorDirection == '';
        }
    });
    $(document).ready(function () {
        $('select').select2({
            selectOnClose: true 
        });
        $('.select2-container').focusin(function () {
            try {
                $(this).siblings('select').select2('open');
            } catch (e) {
            }
        });
        $('select').on('select2:close', function () {
            if (cursorDirection == 'next') {
                this.nextElementSibling.nextElementSibling.focus();
            }
            else if (cursorDirection == 'prev') {
                this.previousElementSibling.focus();
            }
        })
    });

0
投票

用tabbable.js试试这个,我有同样的问题已经解决了

$('select').select2({
  placeholder: 'Select a month'
});
$(function() {
  $(document).off('keydown ,select2:close', '.form-control,.select2-search__field')
  jQuery.extend(jQuery.expr[':'], {
    focusable: function(el, index, selector) {
      return $(el).is('a, button, :input, [tabindex]');
    }
  });
  $(document).on('keydown ,select2:close', '.form-control,.select2-search__field', function(e) {

    if (e.which == 13) {
      e.preventDefault();
      jQuery.tabNext();
    }
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.