【问题标题】:Select onchange with keyboard - do not trigger onchange event until focusout?使用键盘选择 onchange - 在焦点消失之前不要触发 onchange 事件?
【发布时间】:2019-02-28 05:15:36
【问题描述】:
我有一个绑定到更改事件的选择,以便在进行选择时将用户带到新页面。鼠标没问题,但是当我尝试使用键盘的箭头键进行选择时,更改事件会在我按下箭头时触发,而不是等待我退出,所以我只能选择第一个选项我的键盘。
$selectLocation.on('change', function() {
location.href = '/data#' + $(this).val().toUpperCase();
});
如何区分更改功能上的点击和按键,或者使更改功能在按键时不触发?
【问题讨论】:
标签:
javascript
jquery
select
onchange
【解决方案1】:
考虑以下sn-p:
// Sets the redirect based on user activity on #test.
$('#test').on('change', function(e) {
if ($(this).data('clicked')) {
// A click was used to change the select box, redirect.
console.log('clicked redirect');
}
});
// Sets data-keypressed on #test when the down or up arrow key is pressed.
$('#test').on('keydown', function(e) {
var code = e.keyCode || e.which;
if (code === 38 || code === 40) {
// Reset data-clicked.
$(this).data('clicked', false);
// Bind focusout to the redirect.
$('#test').unbind('focusout').bind('focusout', function(e) {
if ($(this).val !== '') {
// An option is selected.
console.log('keyboard focusout redirect');
}
});
}
});
// Sets data-clicked on #test.
$('#test').on('click', function(e) {
// Unbind the focusout event added in the change handler.
$(this).unbind('focusout');
// Set data-clicked to be used in the change handler.
$(this).data('clicked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="test" data-clicked="false">
<option value="">-- Select an Option --</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
这个 sn-p 使用 HTML data 属性来设置选择框是否被 click 更改,并在 @987654326 上更改选择框时在选择框上设置 focusout 事件@。重定向将在单击选择时立即发生,但使用键盘时只会在选择框被聚焦并选择一个值时发生。
【解决方案2】:
由于选择导致(在您的情况下)导航,最简单的解决方案是避免更改事件。而是保存初始值并在单击或模糊时与当前值进行比较。
var defaultValue = $('#select').val();
$('#select').focus();
$('#select').on('click blur', function(event) {
if (defaultValue === $(this).val()) {
return
}
// no need to save with location.href
defaultValue = $(this).val()
console.log($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="option" id="select">
<option value="1">1</option>
<option value="2">2</option>
</select>