更改调用函数时选择框的选项值

Change option value of select box on calling function

本文关键字:选项 选择 调用 函数      更新时间:2023-09-26

我正在使用选择框,其中我有两个选项。当我单击一个名为"重新定位封面"的选项时,它会调用JavaScript函数。函数调用后,它在选择框中显示"重新定位盖"(选择框的默认行为),但我想在调用函数后在选择框中显示默认值(在我的情况下为"更改")。当用户再次单击"重新定位封面"选项时,该功能将再次调用并选择框将返回其默认值,依此类推。以下是我为此编写的代码:

目录

<select id="cars">
  <option value="change" selected="selected">Change</option>
  <option value="rep">Reposition cover</option>
    <div>Reposition cover</div>
</select>

爪哇语

 <script type="text/javascript">
     $(document).ready(function(){
     e1 = document.getElementById('cars');
    if(e1)
    {
        e1.addEventListener('change', function() {
        if(this.value == 'rep'){
         repositionCover();
          /*Execute your script */
        }
        else
        {
    
            }
    });
        }
     
     
    });
     </script>
  

只需重置选择的值

$(document).ready(function(){
  $('#cars').on('change', function() {
    if(this.value == 'rep'){
      this.value = 'change';
      //repositionCover();
    } else {
      
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="cars">
  <option value="change" selected="selected">Change</option>
  <option value="rep">Reposition cover</option>
  <div>Reposition cover</div>
</select>