选择下拉菜单时将触发jQuery事件-但该值不会更改 [英] JQuery event to fire when a drop down is selected -- but the value is not changed

查看:103
本文介绍了选择下拉菜单时将触发jQuery事件-但该值不会更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下拉菜单,我想将一个JQuery事件连接到该事件,如果有人单击它,然后选择已经选择的相同选项,则会触发该事件.

I have a dropdown menu that I want to connect a JQuery event to that fires if someone clicks on it but then selects the same option that is already selected.

我已经使用'change'事件运行了所有程序,但是在某些情况下,用户单击下拉列表并重新选择相同的选项是有效的.如果发生这种情况,我需要触发我的事件处理程序.

I've got everything running using the 'change' event but there are cases where it's valid for the user to click the dropdown and reselect the same option. If that occurs I need my event handler to fire.

我该怎么做?

推荐答案

其他答案似乎都不能提供同时处理所有边缘情况的解决方案(例如,在下拉列表之外单击,然后再次单击它)和/或避免双重事件触发.

Other answers do not seem to provide a solution that both handles all edge-cases (such as clicking outside of the dropdown and then clicking on it again) and/or avoids double events triggering.

第一个技巧是存储从下拉列表集中的那一刻起的值.通常,当下拉值更改后,默认的change()事件用于触发方法changewithRepeats.

The first trick is to store the value from the moment the dropdown is focused. The default change() event is used to trigger the method changewithRepeats when the dropdown value has changed, as normal.

否则,第二次单击聚焦的元素将调用blur(),并且当且仅当下拉值保持与初始值相同时,才强制散焦并触发changewithRepeats.

Otherwise, a second click on the focused element will call blur(), forcing a defocus and triggering changewithRepeats if and only if the dropdown value remains the same as initially.

打开下拉菜单并取消它是不可能的,这是有意的.任何散焦都会调用该方法.所有键盘交互操作都可以正常工作(,但是选择相同值的对blur()的调用对于使用屏幕阅读器的用户来说会有些烦人.

Opening the dropdown and cancelling out of it is not possible, this is intentional. Any defocus will call the method. All keyboard interactions also work (but the call to blur() when selecting the same value will be slightly annoying for users with screenreaders).

下面的焦点状态为0 =未聚焦,1 =聚焦时,2 =聚焦.

Focus state in the below is 0 = unfocused, 1 = when getting focus, 2 = has focus.

$(function () {
  var lastFocusValue = '';
  var focusState = 0;

  var changeWithRepeats = function (newestValue) {
    // Your change action here
  };

  $('select').click (function () {
    if (focusState == 1) { focusState = 2; return; }
    else if (focusState == 2) $(this).blur();
  }).focus(function (e) {
    focusState = 1;
    lastFocusValue = $(this).val();
  }).blur(function () {
    focusState = 0;
    if ($(this).val() == lastFocusValue) {
      // Same value kept in dropdown
      changeWithRepeats($(this).val());
    }
  }).change (function () {
    changeWithRepeats($(this).val());
  });
});

Fiddle具有更多调试输出: https://jsfiddle.net/dsschneidermann/tb5csdhp/15 /

Fiddle has some more debug outputs: https://jsfiddle.net/dsschneidermann/tb5csdhp/15/

这篇关于选择下拉菜单时将触发jQuery事件-但该值不会更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆