仅在单击下拉列表时填充下拉列表

Kin*_*rog 2 html javascript jquery drop-down-menu

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

我试过了,$('select').click但无济于事.

如果您没有任何选项,它可以工作.但如果有当前的选择,没有运气.

Ste*_*fan 8

请尝试使用该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>');
    }
});?
Run Code Online (Sandbox Code Playgroud)

查看简单演示.

UPDATE

这是一个新版本,它使用unbind只触发一次事件处理程序.通过这种方式,您可以在alert不添加任何option元素的情况下使用您来更改条件的结果,如同以前的解决方案所需.

$('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');
});?
Run Code Online (Sandbox Code Playgroud)

希望这就是你要找的东西.