【问题标题】:how to return a string from a function in jQuery as a parameter to the other jQuery function?如何从jQuery中的函数返回一个字符串作为另一个jQuery函数的参数?
【发布时间】:2012-07-18 11:25:34
【问题描述】:

我有一个小问题:我需要将字符串的值从函数 A 传递给函数 B,它会将其作为参数并使用它。

我尝试了以下方法,但它不起作用。

   // first function (A)
   $("a#SayHello").click(function (e) {
       e.preventDefault();

       var x = function () {
               var dt = '{"ProductID": "' + $("input#ProductID").val() + '" , "AffiliationURL": "' + $("input#AffiliationURL").val() + '" , "Quantitiy": "' + $("input#Quantitiy").val() + '" , "PricePerUnit": "' + $("input#PricePerUnit").val() + '" , "commissionAmount": "' + $("input#commissionAmount").val() + '"}';
               return dt.toString();
           };
       alert(x);
       $.B(x);
   });

   // second function
   function B(dt) {

       $.ajax({
           type: 'POST',
           data: dt,
           url: 'http://localhost:4528/WebSite1/WebService.asmx/InsertCommissionRecord',
           contentType: 'application/json; charset=utf-8',
           dataType: 'json',
           success: function (data, textStatus, XMLHttpRequest) {
               alert(data.d);
               alert(XMLHttpRequest);

           },
           error: function (XMLHttpRequest, textStatus, errorThrown) {
               alert(textStatus);
           }
       });
   };

【问题讨论】:

    标签: javascript jquery jquery-plugins


    【解决方案1】:

    我不确定,但你没有执行该功能,试试这个:

    alert(x());
    $.B(x());
    

    【讨论】:

      【解决方案2】:

      尝试调用不带“$.”的 B 函数,只需 B() ,就像任何简单函数一样。

      另外,您可以在 B() 函数中添加一个alert(dt),以检查来自参数的数据。

      【讨论】:

        【解决方案3】:

        代替

        $.B(x);
        

        立即调用 x() 和 B():

        B(x());
        


        为了能够像这样使用B()$.B(),您需要将您的函数添加到 jQuery 的$
        $.B = function(){...
        

        jQuery.B = function(){...
        

        但一般不建议污染$ - 使用自己的命名空间要好得多。

        请看这里:is-it-possible-to-create-a-namespace-in-jquery

        【讨论】:

        • 我刚刚做了以下事情,它对我有用$("a#SayHello").click(function (e) { e.preventDefault(); var x = A(); // alert(x); B(x); }); // first function (A) function A() { var dt = '{"ProductID": "' + $("input#ProductID").val() + '" , "AffiliationURL": "' + $("input#AffiliationURL").val() + '" , "Quantitiy": "' + $("input#Quantitiy").val() + '","commissionAmount": "' + $("input#commissionAmount").val() + '"}'; return dt.toString(); };
        猜你喜欢
        • 2016-07-21
        • 2016-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-26
        • 2013-04-14
        相关资源
        最近更新 更多