2

我无法找出如何通过用户点击下拉菜单来启动点击事件。仅当用户单击很少见的下拉列表时,我才想填充下拉列表。此外,它还取决于页面上选择的其他几个值。所以基本上,如果用户只是简单地点击下拉菜单来查看选项,我该如何触发一个事件。

我试过了,$('select').click但没有用。

如果您没有任何选择,它会起作用。但是,如果有当前的选择,那就没有运气了。

4

3 回答 3

9

尝试改用focus事件,这样select即使使用键盘作为目标,也会填充。

$('select').on('focus', function() {
    var $this = $(this);
    if ($this.children().length == 1) {
        $this.append('<option value="1">1</option><option value="2">2</option>');
    }
});​

查看简单的演示

更新

这是一个使用unbind仅触发事件处理程序一次的新版本。这样您就可以在不添加任何元素的情况下使用您的元素来更改条件的结果,就像以前的解决方案所需的那样。alertoption

$('select').on('focus', function() {

    var $this = $(this);

    // run your alert here if it´s necessary
    alert('Focused for the first time :)');

    // add the new option elements
    $this.append('<option value="1">1</option><option value="2">2</option>');

    // unbind the event to prevent it from being triggered again
    $this.unbind('focus');
});​

希望这就是你要找的。

于 2012-11-19T19:55:39.847 回答
4

它应该工作。在这里,我已经完成了它和它的工作。

$("select").on("click", function() {
    $(this).append("<option>1</option><option>2</option>");
});

更新:http: //jsfiddle.net/paska/bGTug/2/

新代码:

var loaded = false;
$("select").on("click", function() {
    if (loaded)
        return;
    $(this).append("<option>1</option><option>2</option>");
    loaded = true;
});
于 2012-11-19T19:50:33.963 回答
1

点击后自动打开下拉菜单比较棘手:

// Mousedown is used so IE works
$('#select_id').on('focus mousedown', function (e) {
    var data;
    $(this).off('focus mousedown');
    $.ajax({async: false, 
            type: 'GET', 
            url: 'url that returns the options',
            success: function (d) { data = d; }
           });
    $(this).find('option').remove().end().append(data);
    // Prevent IE hang by waiting awhile
    var t = new Date().getTime(); while(new Date().getTime() < t + 200) {}
    return true;
});
于 2017-02-20T14:16:50.113 回答