javascript - 如何在下拉选择上运行 jquery 函数

标签 javascript jquery

我有一个名为 Filtername 的简单下拉列表。我想在从列表中选择一个值时运行一个函数。我已经在下面尝试过

$('#FilterName').change(function() {
         code1;
         code2;
    }

问题是它仅在所选值更改时才起作用。即使用户再次从下拉列表中选择相同的值,我也想运行该函数。因此,我需要在选择值时运行该函数。我尝试了 .select/.submit 函数,但它们不起作用。请帮忙......

最佳答案

摘 self 对 Fire event each time a DropDownList item is selected with jQuery 的回答:

A lot of the current solutions will break in a lot of situations. Any solution that relies on checking the click count twice will be very fickle.

Some scenarios to consider:

  • If you click on, then off, then back on, it will count both clicks and fire.
  • In firefox, you can open the menu with a single mouse click and drag to the chosen option without ever lifting up your mouse.
  • If you use any combination of keyboard strokes you are likely to get the click counter out of sync or miss the change event altogether.
    • You can open the dropdown with Alt+ (or the Spacebar in Chrome and Opera).
    • When the dropdown has focus, any of the arrow keys will change the selection
    • When the dropdown menu is open, clicking Tab or Enter will make a selection

这是一个更全面的扩展:

查看某个选项是否被选中的最可靠方法是使用 change事件,您可以使用 jQuery 的 .change() 处理该事件处理程序。

剩下唯一要做的事情是确定是否再次选择了原始元素。
这个问题已经被问了很多次( onetwothree ),但在任何情况下都没有得到很好的答案。

最简单的做法是检查 option:selected 元素上是否有 clickkeyup 事件<强>但是Chrome, IE, and safari don't seem to support events on option elements ,即使它们位于 w3c recommendation

Select 元素内部似乎是一个黑框。如果您监听其上的事件,您甚至无法判断事件发生在哪个元素上或者列表是否打开。

接下来最好的事情似乎是处理 blur 事件。这将表明用户已将注意力集中在下拉菜单上(可能看到了列表,也可能没有)并决定保留原始值。要立即继续处理更改,我们仍将订阅 change 事件。为了确保我们不会重复计数,如果引发更改事件,我们将设置一个标志,这样我们就不会触发两次:

代码:

(function ($) {
    $.fn.selected = function (fn) {
        return this.each(function () {
            $(this).focus(function () {
                this.dataChanged = false;
            }).change(function () {
                this.dataChanged = true;
                fn(this);
            }).blur(function (e) {
                if (!this.dataChanged) {
                    fn(this);
                }
            });
        });
    };
})(jQuery);

然后像这样调用:

$("#dropdownid").selected(function (e) {
    alert('You selected ' + $(e).val());
});

Updated example in jsFiddle

关于javascript - 如何在下拉选择上运行 jquery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23397319/

相关文章:

asp.net - 我可以在我的 ASP.net 网站/项目中使用 jQuery 吗?

javascript - 如何知道回调函数已触发?

javascript - jQuery 中的计时/等待

javascript - 当其他 radio 取消选择时,React Radio onChange 不起作用

javascript - 使网页实时运行并支持多用户的最佳方式

javascript - JSON 获取对象索引

c# - ASP.NET 双列表框使用 JQuery 更新了客户端,以及如何在服务器端检索结果

javascript - 混合水平和垂直滚动

javascript - 从列表中删除元素 - JQuery/JavaScript

javascript - 如何从Ajax返回字符串中解析参数