首页 > 解决方案 > 防止重复函数onchange事件jQuery

问题描述

我在下面有这个片段

$(document).ready(function(){
  $("#selectTest").change(function(e){
    if($(this).val() == "01"){
      $(".show").hide();
    }else{
      $(".show").show();
    };
  })
})
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
    <div class="show">
        Sample Text
    </div>
    <select name="test" id="selectTest">
        <option value="00"></option>
        <option value="01">Click this to hide text</option>
        <option value="02">Click this to show text</option>
    </select>
</body>
</html>

上面的片段看起来不错,但是当页面加载时从第一个选择的选项时我遇到了麻烦。我必须单击不同的按钮才能使该hide功能起作用。我通过在我的代码中添加 解决了这个问题,if ... else以便在页面加载时隐藏功能将正常运行。

$(document).ready(function(){
  $("#selectTest").change(function(e){
    if($(this).val() == "01"){
      $(".show").hide();
    }else{
      $(".show").show();
    };
  })

   if($("#selectTest").val() == "01"){
      $(".show").hide();
    }else{
      $(".show").show();
    };
})

上面的代码看起来不合适,因为我必须重复我所做的功能,有没有更好的方法来解决这个问题?

标签: javascriptjqueryhtml

解决方案


您可以使用 jQuery触发事件(更改) ,而不是编写两次代码.trigger()

$("#selectTest").trigger('change');

工作代码示例:

$(document).ready(function(){
  $("#selectTest").change(function(e){
    if($(this).val() == "01"){
      $(".show").hide();
    }else{
      $(".show").show();
    };
  });
 $("#selectTest").trigger('change');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="show">
    Sample Text
</div>
<select name="test" id="selectTest">
    <option value="00"></option>
    <option value="01">Click this to hide text</option>
    <option value="02">Click this to show text</option>
</select>


推荐阅读