gpt4 book ai didi

javascript - 我怎样才能调用函数?

转载 作者:行者123 更新时间:2023-12-02 17:15:00 25 4
gpt4 key购买 nike

假设单击按钮后 - 我们发送请求。我有一个结构如下的 jquery 插件:

(function($){

$.myPlugin = {
defaults: {}
};

$.fn.extend({
/**
* Initializes the plugin
*/
myPlugin: function(settings)
{
return this.each(function() {

settings = $.extend({}, $.myPlugin.defaults, settings);
$.data(this, "myPlugin", settings);

var self = this;

$('#button', self).on('click', function () {
functionTwo.call(this);
});
});
}
});

function functionOne()
{
alert(1);
}

function functionThree()
{
alert(3);
}

function functionTwo(self)
{
$.ajax({
url: '/some_url',
type: 'GET',
success: function (response) {

// Here I need to call function depends on response.funcName.
// Where funcName can be functionThree, functionOne, etc.
// I try something like that: window[funcName], etc. But it was
// not successfully.
}
});
}
})(jQuery);

在ajax响应之后的functionTwo中,我需要调用依赖于response.funcName的函数。其中response.funcName可以是functionThree,functionOne等。我尝试了类似的东西:windowfuncName等。但没有成功。

我不明白这个函数(functionThree、functionOne 等)在哪里声明,在什么范围内?我怎样才能动态调用它?

最佳答案

尝试将函数放入对象中,以便您可以使用括号语法引用它们:

(function($){
var functions = {
functionOne: function() {
alert(1);
},
functionThree: function() {
alert(3);
},
functionTwo: function(self) {
$.ajax({
url: '/some_url',
type: 'GET',
success: function (response) {
functions[response.funcName]();
}
});
}
}

$.myPlugin = {
defaults: {}
};

$.fn.extend({
/**
* Initializes the plugin
*/
myPlugin: function(settings)
{
return this.each(function() {

settings = $.extend({}, $.myPlugin.defaults, settings);
$.data(this, "myPlugin", settings);

var self = this;

$('#button', self).on('click', function () {
functions.functionTwo.call(this);
});
});
}
});
})(jQuery);

关于javascript - 我怎样才能调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24511803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com