我正在使用许多老化的应用程序,我需要做的是进入应用程序并提取 html 表格并将它们显示在新页面上,然后更新那里的代码样式。我已经为 ajax 调用创建了一个插件,我想为其提供 url 和目标 ID 的参数,然后将它们显示在页面的不同部分中。问题是它采用范围内的最后一个参数,并在 doc.ready 内的所有函数调用中使用它们。
(function($){
$.fn.getAppData = function(options) {
data = $.extend({
target: $(this),
id: "body",
url: "/error/404error.html",
callback: function(){}
}, options );
$.ajax({
url: data.url,
cache: false
})
.done(function( html ) {
//alert(data.id);
$display = $(html).find('div'+data.id);
data.target.append($display);
options.callback.call(this);
})
.fail(function() {
alert('Error loading '+data.id+' data.');
});
}
}
}(jQuery));
以下是 doc.ready 语句中的调用:
$(document).ready(function(e) {
$('#bulletinBoard').getAppData({
target: $('#bulletinBoard'),
id: '#tabs-1',
url: '/webapps/BulletinBoard/default.cfm',
callback: function() {
//manipulate the new loaded html here
}
});
$('#VTCSchedule').getAppData({
target: $('#VTCSchedule'),
id: "#vtcInfo",
url: "/webapps/VTCInfo/default.cfm",
callback: function() {
//manipulate the new loaded html here
}
});
$('#askMGMT').getAppData({
target: $('#askMGMT'),
id: "#askMGMT",
url: "/webapps/askthera/AskTheRIIManagement.asp",
callback: function() {
//manipulate the new loaded html here
}
});
});
这可能是一个愚蠢的举动,但我没有看到问题,而且我没有太多时间。提前致谢。
最佳答案
记下您的ajax url:data.url
。这始终是您当前拥有的“/error/404error.html”。您应该从 options
中提取 data.url:
$.fn.getAppData = function(options) {
$this = $(this);
data = $.extend({
id: options.id, // <- this is now dynamic
url: options.url, // <- this is now dynamic
callback: function(){}
}, options );
与 data.id
相同。
编辑
我错了!问题出在 data =
上。由于缺少 var
,因此您将 data
分配给全局范围,从而在每次新调用此方法时覆盖它。我会使用以下内容:
(function($){
$.fn.getAppData = function(options) {
$this = $(this);
var data = $.extend({ // <- Only available in current scope because of "var"!
id: "body",
url: "/error/404error.html",
callback: function(){}
}, options );
$.ajax({
url: data.url,
cache: false
})
.done(function( html ) {
//alert(data.id);
$display = $(html).find('div'+data.id);
$this.append($display);
options.callback.call(this);
})
.fail(function() {
alert('Error loading '+data.id+' data.');
});
//Also note, that there was an extra bracket "}" here
}
}(jQuery));
关于javascript - 我的 jQuery 插件参数无法正确触发时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29563630/