douyin9987 2014-05-31 11:06
浏览 34
已采纳

调用表单php里面的一个函数jquery [复制]

This question already has an answer here:

i'd like to call a jquery function from php. I tried this way, but the jquery functions are not called.

jq.action.js

$(function() {

  $("#reset" ).click(function(e){       
    e.preventDefault();
    reset_fields();
  });

  function reset_fields(){
    $(":input").prop('selectedIndex', 0);
  }

  function error_msg(){
    alert("Error");
  }

});

index.php

<script type='text/javascript' src='jquery-1.11.1.min.js'></script>
<script type='text/javascript' src='jq.action.js'></script> 

<?php
if ($_POST['id'] == '1') {

       echo '<script>reset_fields();</script>';

} else {

       echo '<script>error_msg();</script>';
}
?>

ReferenceError: reset_fields is not defined

how can I call from php the functions inside jquery? thanks!

</div>
  • 写回答

2条回答 默认 最新

  • douche3791 2014-05-31 11:34
    关注

    Your problem is JavaScript scoping: the function you're trying to call is not accessible from everywhere.

    $(function() {
        function reset_fields(){
            // this function is only accessible to things inside $(function(){...
        }
    }
    

    That means that you can't access it directly. However, if you place the function outside, it will work:

    function reset_fields() {
        // now this function is globally accessible from anywhere
    }
    
    $(function() {
        // you can still call reset_fields() from here
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记