将这个本地js变量作为参数传递给一个新函数

pass this local js variable as an argument to a new function

本文关键字:一个 新函数 函数 js 变量 参数传递      更新时间:2023-09-26

我读过几篇关于在javascript中将局部函数变量传递给新函数的文章,但在我自己的特殊情况下仍然遇到麻烦。

我试图将给定给data: function (term, page)term参数传递给它下面的generateUrl函数。this.term = termwindow.term = term(我知道这是不好的做法)不工作。我应该尝试在$(document).ready(function)或两个内部函数之外声明term变量,还是应该将generateUrl定义移动到$("#example").select2函数内部?

$(document).ready(function(){
  $("#example").select2({
      ajax: {
          url: generateUrl(),
          data: function (term, page) {
            this.term = term; // i want to pass this local variable to generateUrl
          }
      }
  });
  function generateUrl(term) {
    (function ($) {
    var args = 'keywords=' + term;
    return args;
    }
    (jQuery));
  }
});
$(document).ready(function(){
 $("#example").select2({
  ajax: {
      url: generateUrl(), /* You are calling generateUrl without parameter, 
                               this will cause error
                             Did you actualy mean generateUrl(term) ? */
      data: function (term, page) {
        this.term = term; // i want to pass this local variable to generateUrl
        generateUrl( this.term ); /* Is this what you want to do?  */
      }
  }
});
function generateUrl(term) {
  (function ($) {
    var args = 'keywords=' + term;
    return args;
  }
(jQuery));

}});

您应该查看一下select2文档,"加载远程数据"部分的示例似乎正是您正在寻找的。基于此,我认为你的代码应该是:

$(document).ready(function(){
  $("#example").select2({
      ajax: {
          url: "", // replace that empty string with your ajax base url 
                   // (without any parameters)
          data: function (term, page) {
              return { keywords : term };
          }
      }
  });
});