jQuery/Ajax - $.ajax() 将参数传递给回调 - 使用的好模式? [英] jQuery / Ajax - $.ajax() Passing Parameters to Callback - Good Pattern to Use?

查看:21
本文介绍了jQuery/Ajax - $.ajax() 将参数传递给回调 - 使用的好模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始使用的 JavaScript 代码:

JavaScript code I'm starting with:

function doSomething(url) {  
   $.ajax({
      type: "GET",  
      url: url,  
      dataType: "xml",  
      success: rssToTarget  
   });  
}    

我想使用的模式:

//where elem is the target that should receive new items via DOM (appendChild)
function doSomething(url, elem) {
   $.ajax({
      type: "GET",
      url: url,
      dataType: "xml",
      success: rssToTarget(elem)
   });
}  

我不认为我可以让回调以这种方式工作,对吗?什么是正确的模式?我不想使用全局变量来临时保存 elem 或 elem 名称.

I don't think I can get the callback to work this way, right? What is the proper pattern? I don't want to use global variables necessarily to temporarily hold the elem or elem name.

推荐答案

像这样...

function doSomething(url, elem) {
  $.ajax({
     type: "GET",
     url: url,
     dataType: "xml",
     success: function(xml) {
       rssToTarget(xml, elem);
     }
  });
}

回答您的评论:使用匿名函数会影响性能吗?

这篇关于jQuery/Ajax - $.ajax() 将参数传递给回调 - 使用的好模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆