简体   繁体   English

调用用户定义的jQuery函数

[英]Calling a user defined jQuery function

I'm a javascript newbie and I'm trying to call a jQuery function in this way: 我是一名JavaScript新手,并且尝试通过这种方式调用jQuery函数:

function getProducts(){
      $.post("products.php",
      {
        customer_ID:$("#customers").val()
      },
      function(data,status){
        return status && data !== "";
      });
};

$(document).ready(function(){
    $("#customers").change(function(){
        if(getProducts){
            alert("trovato");

            $("#products").prop("disabled", false);
            $("#products").html(data);
        }else{
            alert("non trovato");

            $("#products").empty();
            $("#products").prop("disabled", true);
        }
    });
});

The if-else statement in the ready doesn't work although the function getProducts works properly. 尽管函数getProducts正常工作,但ready中的if-else语句不起作用。 The problem, I suppose, is in the function call. 我想问题出在函数调用中。 What am I wrong with this? 我有什么错吗? Thank you. 谢谢。

You need to wrap the response with a callback, like so: 您需要使用回调包装响应,如下所示:

function getProducts(callback){
      $.post("products.php",
      {
        customer_ID:$("#customers").val()
      },
      function(data,status){
         callback(status && data !== "");
      });
};

$(document).ready(function(){
    $("#customers").change(function(){
        getProducts(function(status) {
           if(status){
             alert("trovato");

             $("#products").prop("disabled", false);
             $("#products").html(data);
           }else{
             alert("non trovato");

             $("#products").empty();
             $("#products").prop("disabled", true);
           }
        });

    });
});

I'm not quite sure if this will work because of the asynchronized call inside of the function. 由于函数内部的异步调用,我不太确定这是否能正常工作。

The obvious mistake is that you have to call a function like that: function() . 明显的错误是,您必须调用类似的函数: function() You just forgot the parentheses. 您只是忘记了括号。

If it won't work after that fix, you have to rework your program to use callbacks where you have asynchron calls. 如果在该修复程序后仍无法正常工作,则必须对程序进行重新设计以在具有异步调用的地方使用回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM