我的印象是,我可以通过执行这个$(this).val()来获取一个选择输入的值;并将onchange参数应用到select字段。

只有在引用ID时,它才会起作用。

我怎么用这个。


当前回答

只使用JS

 let select=document.querySelectorAll('select') 
  select.forEach(function(el) {
    el.onchange =  function(){
     alert(this.value);
      
  }}
  )

其他回答

jQuery(document).ready(function(){

    jQuery("#id").change(function() {
      var value = jQuery(this).children(":selected").attr("value");
     alert(value);

    });
})

这对我来说很管用。我尝试了其他所有方法,但都没有成功:

<html>

  <head>
    <title>Example: Change event on a select</title>

    <script type="text/javascript">

      function changeEventHandler(event) {
        alert('You like ' + event.target.value + ' ice cream.');
      }

    </script>

  </head>

  <body>
    <label>Choose an ice cream flavor: </label>
    <select size="1" onchange="changeEventHandler(event);">
      <option>chocolate</option>
      <option>strawberry</option>
      <option>vanilla</option>
    </select>
  </body>

</html>

摘自Mozilla

请注意,如果这些不工作,这可能是因为DOM还没有加载,您的元素还没有找到。

若要修复,请将脚本放在正文的末尾或使用文档就绪

$.ready(function() {
    $("select").on('change', function(ret) {  
         console.log(ret.target.value)
    }
})

只使用JS

 let select=document.querySelectorAll('select') 
  select.forEach(function(el) {
    el.onchange =  function(){
     alert(this.value);
      
  }}
  )
$('#select_id').on('change', function()
{
    alert(this.value); //or alert($(this).val());
});



<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select id="select_id">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
</select>