获取每个选择元素的选定值并登录到控制台

我下面的功能是记录一个值到控制台,而不是2个值。最终,我的项目将有多个选择元素,我需要通过一个函数传递每个选择元素的值。

HTML:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<div class="choice">
  <select name="selecttype">
    <option value="0">choice 1</option>
    <option value="1">choice 2</option>
    <option value="" selected>N/A</option>
  </select>
</div>
<div class="choice">
  <select name="selecttype">
    <option value="0">choice 1</option>
    <option value="1">choice 2</option>
    <option value="" selected>N/A</option>
  </select>
</div>
<button id="logvalues" type="submit" class="btn btn-success">log values to console</button>

Javascript:

$("#logvalues").click(function() {
   $("option:selected").each(function(){
      console.log($("option:selected").val());
  });
})
评论
  • 贪婪
    贪婪 回复

    You just need to pass the current context using this like:

    $("#logvalues").click(function() {
      $("option:selected").each(function() {
        console.log( $(this).val() );
      });
    })
    

    演示:

    $("#logvalues").click(function() {
      $("option:selected").each(function() {
        console.log($(this).val());
      });
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
    <div class="choice">
      <select name="selecttype">
        <option value="0">choice 1</option>
        <option value="1">choice 2</option>
        <option value="" selected>N/A</option>
      </select>
    </div>
    <div class="choice">
      <select name="selecttype">
        <option value="0">choice 1</option>
        <option value="1">choice 2</option>
        <option value="" selected>N/A</option>
      </select>
    </div>
    <button id="logvalues" type="submit" class="btn btn-success">log values to console</button>