功能只能与$('#element')一起使用.Click()

时间:2011-02-17 13:53:18

标签: javascript jquery

我使用jQuery来调用带有两个参数的PHP脚本,from和to,用于查询两者之间的限制。我正在建造一个呕吐物。

问题是这可以正常使用:

$(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中仅加载背景!什么是错的......?

4 个答案:

答案 0 :(得分:3)

您需要将第一行更改为:

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

我很惊讶它完全有效,因为在你的例子中调用document.ready应该会抛出一个错误。

答案 1 :(得分:3)

我不确定它有多重要,但我会把这个功能放在$(document).ready(之外。

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 ...
}

$(document).ready(function(){
    display_from_server();   
});

答案 2 :(得分:0)

我会在第二种情况下在compute_to_value()中设置一个断点,并确保当$(文件).ready首次运行时,其计算的内容实际上已准备就绪

答案 3 :(得分:0)

我的猜测是calculate_to_value()有一个错误。一些想法:

  1. 检查JavaScript错误控制台。也许抛出异常
  2. 将一些日志语句添加到calculate_to_value()
  3. 如果将calculate_to_value()替换为from+10
  4. 会怎样?