【问题标题】:HOw can I use onchange in jquery我如何在 jquery 中使用 onchange
【发布时间】:2021-08-27 18:26:36
【问题描述】:

以下代码未调用 onchange 函数:

<input  id="department" name="department" />
                                

<script type="text/javascript">
$jq("#department").on('change',function(){
        console.log('Inside department onchange');
        validateDepartment();
    });
</script>                       

【问题讨论】:

  • 你在哪里定义了$jq
  • 另外,validateDepartment() 应该做什么?你能添加你的完整代码吗
  • 什么是 $jq ? ...
  • 您应该使用$jQuery 而不是$jq

标签: javascript onchange


【解决方案1】:

您的 jQuery 代码中有一个错误。您需要使用 'jQuery' 而不是 '$jq',否则它会在控制台中显示类似“Uncaught ReferenceError: $jq is not defined”的错误。

jQuery("#department").on('change',function(){
    console.log('Inside department onchange');
    validateDepartment();
});

【讨论】:

    【解决方案2】:

    我不确定你为什么有$jq,因为那不是正确的语法。

    基本语法是:$(selector).action()

    定义/访问 jQuery 的 $ 符号

    用于“查询(或查找)”HTML 元素的(选择器)

    要在元素上执行的 jQuery action()

    这是一个工作示例:

    <!DOCTYPE html>
    <html>
      <head>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      </head>
      <body>
        
    <input  id="department" name="department" />
      </body>
      <script>
      $("#department").on('change',function(){
            console.log('Inside department onchange');
            validateDepartment()
    });
        
        function validateDepartment(){
        var inputdept = $( "#department" ).val();
            alert(inputdept + " Department is valid!")
        }
      </script>
    </html>

    【讨论】:

      【解决方案3】:

      有一个语法错误将 $jq 替换为 $ 像这样

      $("#department").on('change',function(){
          console.log('Inside department onchange');
          validateDepartment();
      });
      

      你可以这样做

      $(document).on('change','#department',function(e){
         // code 
      });
      

      $('#department').change(function(e){
             // code 
      });
      

      您还可以在输入字段中附加 onchange 属性,以便像这样处理更改事件

      <input  id="department" name="department" onchange="myFunc(this)"/>
      

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-07
        • 2021-03-19
        • 2010-11-29
        • 1970-01-01
        • 2020-10-11
        • 2021-07-27
        相关资源
        最近更新 更多