选择什么事件来委托<select>到选定的选项>

What event(s) to choose to delegate a handler from <select> to the selected <option>?

本文关键字:选项 select 事件 什么 选择      更新时间:2023-09-26

当在<select>控件中选择另一个<option>时,可以用<select>触发的处理程序以相当直接的方式处理此事件。但是,由于某些原因,对于我的项目来说,使用委托的<option>触发处理程序要方便得多。我尝试使用不同的事件来触发和委托所需的处理程序。结果令人不满意:

  • onfocus, onchangeonkeyup处理程序仅在<select>控件上触发,而不会在嵌套的<option>上触发。
  • onclick处理程序根据需要工作并被委托(在选定的<option>上触发)。然而,使用这个处理程序显然没有意义,因为select控件中的另一个option也可以通过键盘选择,而不仅仅是通过鼠标。

我说的对吗?我是否错过了本例中可以使用的任何标准DOM事件?或者我只能使用一种多边形,像jQuery的focusinfocusout ?

从讨论中可以得出,没有满足指定要求的DOM事件。

我不确定我是否完全理解你的需求,但我会尽量回答。

当你在谈论jQuery时,我有这个解决方案:

$("#my-select").change(function() {
    // $(this) refers to the select element
    $(this).find("option:selected").each(function() {
        // this function is called only once per change
        // $(this) refers to the selected option
    })
});

实例:

$("#my-select").change(function() {
  // $(this) refers to the select element
  $("#s_value").text($(this).val());
  $("#s_text").text($(this).find("option:selected").text());
  $(this).find("option:selected").each(function() {
    // this function is called only once per change
    // $(this) refers to the selected option
    $("#o_value").text($(this).val());
    $("#o_text").text($(this).text());
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="my-select">
  <option value="1">Option 1</option>
  <option value="2">Option 2</option>
  <option value="3">Option 3</option>
</select>
<br>SELECTED (FROM SELECT) :
<br>Value : <span id="s_value"></span>
<br>Text : <span id="s_text"></span>
<br>
<br>SELECTED (FROM OPTION) :
<br>Value : <span id="o_value"></span>
<br>Text : <span id="o_text"></span>
<br>
<br>