简体   繁体   English

当选择列表文本更改时(在onchange事件触发之前)如何触发回调函数?

[英]How to trigger a callback function when select list text changes (before onchange event fires)?

I have a <select> field like the below: 我有一个<select>字段,如下所示:

<select id="my-list" class="default">
    <option value=0 selected disabled>Select an item</option>
    <option value=1>First Item</option>
    <option value=2>Second Item</option>
    <option value=3>Third Item</option>
</select>

The default class on the <select> element sets the color to red (indicating to the user that an option needs to be selected here). <select>元素上的默认类将颜色设置为红色(向用户指示需要在此处选择一个选项)。

Once the user selects an item the class is removed so the color changes to black. 一旦用户选择了一个项目,该类将被删除,因此颜色变为黑色。

Now what I'm trying to achieve is that the color changes as soon as the text in the select box changes. 现在,我要实现的是,选择框内的文本更改后颜色就会立即更改。 The onchange event only fires if the user clicks on an item in the list or presses ENTER or the element loses focus. 仅当用户单击列表中的项目或按ENTER或元素失去焦点时,才会触发onchange事件。

But if the user hits S for example the text will change to "Second item" and the color remains red until he presses ENTER or tabs out of the field. 但是,例如,如果用户按下S ,则文本将变为“第二项”,并且颜色保持红色,直到他按下ENTER或该字段之外的选项卡为止。

Listening for keydown events doesn't work because if the user hits say X the event fires but the text won't change because there is no matching item. 监听keydown事件不起作用,因为如果用户点击说X,则事件触发,但文本不会更改,因为没有匹配项。

One possible solution could be to use the keydown event and then compare the text to "Select an item" though it doesn't seem very elegant. 一种可能的解决方案是使用keydown事件,然后将文本与“选择一个项目”进行比较,尽管它看起来不太优雅。 And how would I get the text that is displayed? 以及如何获取显示的文本? jQuery's .text() or .html() return all the options, not just what is displayed. jQuery的.text().html()返回所有选项,而不仅仅是显示的内容。

After writing the last paragraph of my question the answer came to me. 在写了我问题的最后一段之后,答案就来了。

Typing into a select box or using the up and down arrow keys will set the selected attribute to the option displayed. 键入选择框或使用向上和向下箭头键会将selected属性设置为显示的选项。 Using the keyup event instead of the keydown event can then be used to simply check the value of the selected option and if it's not 0 the class is removed and the color changes. 然后,可以使用keyup事件而不是keydown事件来简单地检查所选选项的值,如果该值不为0,则将删除该类并更改颜色。

$("#my-list").keyup(function(){
    if ($("#my-list option:selected").val() !== 0){
        $("#my-list").removeClass("default");
    }
});

It seems a bit clumsy so perhaps there is a better way, but it works. 似乎有点笨拙,所以也许有更好的方法,但是它可行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM