【问题标题】:How to catch the event of change of <select > with jQuery?如何用 jQuery 捕捉 <select > 的变化事件?
【发布时间】:2010-11-27 01:27:03
【问题描述】:
<select id="target">
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
</select>

说,我想根据选择的值做一些处理。

【问题讨论】:

  • 如果他们点击已经选择的项目怎么办?

标签: jquery event-handling


【解决方案1】:
$('#target').change( function() {
   $(this).find(":selected").each(function () {
            console.log( $(this).val() );
    });
 });

【讨论】:

    【解决方案2】:
    $("#target").change( function() {
      var selectedOption = $("#target option:selected");
      var selectedValue = selectedOption.val();  // gets the selected value
      var selectedText = selectedOption.text();  // gets the selected text
    });
    

    【讨论】:

    • 请在您的答案中添加有关如何在事件处理程序中获取所选值的详细信息(在 OP 中提到)。
    • 您的初始选择器似乎有一些随机字符']
    • 另外,将selected 替换为selectedOption 或相反
    【解决方案3】:
    $("#target").change( function() {
        alert($("#target option:selected").val());
    });
    

    如果此人没有更改选项,而只是单击下拉菜单并选择相同的项目,您可能还需要考虑这一点:

    $("#target option").click( function() {
         alert($("#target option:selected").val());
    });
    

    【讨论】:

      【解决方案4】:

      您可以通过以下方式获取选定的值和文本:

      $("#target").change(function() {
        var selectedValue = $(this).val(),
            selectedText = $('option:selected', this).text();
        // ...
      });
      

      【讨论】:

        【解决方案5】:

        接受的答案是可以的,但不要捕捉按键(箭头键或字母键)所做的更改。

        这是一个更好的方法:

        $('#target').bind("change keyup",function() {
           $(this).find(":selected").each(function () {
             // do something amazing here
           });
        });
        

        【讨论】:

          【解决方案6】:

          使用箭头函数,可以:

          $('#target').change((e) =>{
                  console.log(e.currentTarget.value);
                  console.log(e.currentTarget.textContent);
           });
          

          this 替换为event.currentTarget

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-05-24
            • 2014-10-09
            • 1970-01-01
            • 1970-01-01
            • 2018-08-31
            • 2012-07-21
            • 2018-10-13
            相关资源
            最近更新 更多