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条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改