Javascript 在点击和页面加载时运行JS函数

Javascript 在点击和页面加载时运行JS函数,javascript,jquery,html,Javascript,Jquery,Html,我有一个多步骤表单,它使用JS根据用户输入动态显示/隐藏表单的各个部分。当用户第一次浏览表单时,它可以完美地工作。但是,如果返回一步,则会显示所有应隐藏的div。处理此问题的JS函数在单击时运行。我需要它在页面加载和单击时运行,因此如果用户返回到上一步,控制显示/隐藏块('.security_sub_type')的输入将反映在表单中 $(function() { $(document).on('change','.security_sub_type',function ()

我有一个多步骤表单,它使用JS根据用户输入动态显示/隐藏表单的各个部分。当用户第一次浏览表单时,它可以完美地工作。但是,如果返回一步,则会显示所有应隐藏的div。处理此问题的JS函数在单击时运行。我需要它在页面加载和单击时运行,因此如果用户返回到上一步,控制显示/隐藏块('.security_sub_type')的输入将反映在表单中

    $(function() {
      $(document).on('change','.security_sub_type',function () {
         var OBJ = $(this).closest('div.nested-fields')
          OBJ.find(".address").hide();
          OBJ.find(".serial_number").hide();
          OBJ.find(".registration_number").hide();
          if($(this).val()=="Commercial Property"){
              OBJ.find(".address").show();
              OBJ.find(".serial_number").hide();
              OBJ.find(".registration_number").hide();
          }
          if($(this).val()=="Residential Property"){
              OBJ.find(".address").show();
              OBJ.find(".Equipment").hide();
              OBJ.find(".registration_number").hide();
          }
          if($(this).val()=="Machinery"){
              OBJ.find(".registration_number").hide();
              OBJ.find(".address").hide();
              OBJ.find(".serial_number").show();
          }
          if($(this).val()=="Equipment"){
              OBJ.find(".address").hide();
              OBJ.find(".serial_number").show();
              OBJ.find(".registration_number").hide();
          }
          if($(this).val()=="Vehicle"){
              OBJ.find(".address").hide();
              OBJ.find(".serial_number").hide();
              OBJ.find(".registration_number").show();
          }
          if($(this).val()=="Inventory"){
              OBJ.find(".address").hide();
              OBJ.find(".serial_number").hide();
              OBJ.find(".registration_number").hide();
          }
          if($(this).val()=="Accounts Receivable"){
              OBJ.find(".address").hide();
              OBJ.find(".serial_number").hide();
              OBJ.find(".registration_number").hide();
          }
      }).change();
    });

如果允许我使用自插,我就编写了一个小型库,将这类事情简单化。它作用于页面加载、更改为其他输入以及除此之外的更多功能@Utkanos欢迎您首先在不使用第三方工具的情况下解决问题,然后展示第三方工具(您的库)如何将其简化并使其更易于解决。您已经使用jQuery在DOM就绪(页面加载)上运行JavaScript代码,使用
$(function(){/*此代码在DOM就绪*/})
方法。我建议将
on()
调用中的代码移动到一个单独的函数中,然后从
on()
回调和dom ready调用该函数。“处理此操作的JS函数在单击时运行。”?仅在OP
$(文档)的
js
中出现
change
事件。在('change','security_sub_type',function(){//do stuff})。change()
?尝试添加
$(文档)。在('change click,function(){//do stuff})上。触发器(“click”)