如何将jQuery中某个函数的字符串作为参数返回给另一个jQuery函数

how to return a string from a function in jQuery as a parameter to the other jQuery function?

本文关键字:jQuery 函数 参数 返回 另一个 字符串      更新时间:2023-11-01

我有一个小问题:我需要将字符串的值从函数a传递给函数B,函数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);
           }
       });
   };

我不确定,但你没有执行函数,试试这个:

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

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

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

而不是

$.B(x);

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

B(x());


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

$.B = function(){...

jQuery.B = function(){...

但通常不建议污染$——最好使用自己的命名空间。

请参阅此处:是否可以在-jquery 中创建命名空间