Javascript 函数只能在$(';#元素';)下正常工作。单击()

Javascript 函数只能在$(';#元素';)下正常工作。单击(),javascript,jquery,Javascript,Jquery,我使用jQuery调用PHP脚本,其中包含两个参数from和to,用于查询MySQL,这两个参数之间有一个限制。我在建造一个异教徒的东西 问题在于,使用以下方法可以正常工作: $(document.ready(function(){ function display_from_server(){ from = calculate_from_value(); // first run 0, second run 11, third run 22 ... to = c

我使用jQuery调用PHP脚本,其中包含两个参数from和to,用于查询MySQL,这两个参数之间有一个限制。我在建造一个异教徒的东西

问题在于,使用以下方法可以正常工作:

$(document.ready(function(){

   function display_from_server(){
      from = calculate_from_value(); // first run 0, second run 11, third run 22 ...
      to = calculate_to_value();  // first run 10, second run 21, third run 32 ...

      //.. sends 0 and 10 to server and display response on screen.
   }

   $('#button').click(function(){
     display_from_server();
   });
});
但将其更改为此将不再有效:

$(document.ready(function(){

   function display_from_server(){
      from = calculate_from_value(); // first run 0, second run 11, third run 22 ...
      to = calculate_to_value();  // first run 10, second run 21, third run 32 ...

      //.. supposed to send 0 and 10 to server, but sends 0 and 0 ! ?
   }

   display_from_server();

});

因此,当作为按钮单击的回调函数调用时,它可以工作,但直接调用它不起作用!在FF中,除了从服务器加载数据外,其余页面都会加载。在Chrome中,只加载背景!到底怎么了

您需要将第一行更改为:

//JQuery adds the "ready" method to the document object
$(document).ready(function(){
  //rest of the code
});

我很惊讶它居然能工作,因为在您的示例中调用document.ready会引发错误。

您需要将第一行更改为:

//JQuery adds the "ready" method to the document object
$(document).ready(function(){
  //rest of the code
});

我很惊讶它居然能工作,因为在您的示例中对document.ready的调用会抛出一个错误。

在第二种情况下,我会在side calculate\u to\u value()中放置一个断点,并确保在$(document)时它的计算所依据的内容实际上已经准备好了。ready first运行时

我会在side calculate\u to\u value()中放置一个断点在第二种情况下,请确保当$(document).ready第一次运行时,它的计算来源实际上已经准备好了。

我猜
calculate\u to\u value()
有一个bug。一些想法:

  • 检查JavaScript错误控制台。可能引发了异常
  • 将一些日志语句添加到
    calculate\u to\u value()
  • 如果将
    calculate_to_value()
    替换为
    from+10
    ,会发生什么情况

  • 我猜
    计算到值()
    有一个bug。一些想法:

  • 检查JavaScript错误控制台。可能引发了异常
  • 将一些日志语句添加到
    calculate\u to\u value()
  • 如果将
    calculate_to_value()
    替换为
    from+10
    ,会发生什么情况

  • 我不确定它有多重要,但我会将函数放在
    $(document.ready(
    )之外


    我不确定它有多重要,但我会将函数放在
    $(document.ready(
    )之外

    您在
    $(document.ready
    处有一个打字错误您在
    $(document.ready