Javascript 调用用变量标识的jQuery lib函数

Javascript 调用用变量标识的jQuery lib函数,javascript,jquery,oop,function,variables,Javascript,Jquery,Oop,Function,Variables,我使用jQuery函数构建循环html 我希望通过$.append(),$.before(),以及$.after()等,为我的函数提供更大的灵活性 目前,我做了一些类似的事情 $.fn.appendRecurringHTML = function(domInsertMethod, domInsertID, htmlToInsert) { if(domInsertMethod == 'append'){ $(domInsertID).append(htmlToInsert)

我使用jQuery函数构建循环html

我希望通过
$.append()
$.before()
,以及
$.after()
等,为我的函数提供更大的灵活性

目前,我做了一些类似的事情

$.fn.appendRecurringHTML = function(domInsertMethod, domInsertID, htmlToInsert) {
    if(domInsertMethod == 'append'){
        $(domInsertID).append(htmlToInsert);
    }
    else if(domInsertMethod == 'before'){
        $(domInsertID).before( ...
}
但我更喜欢(伪)

但这对我不起作用

这可能吗?如果是,怎么做?

试试这个:

$(domInsertID)[domInsertMethod](htmlToInsert);
这种方法首先使用domInsertID创建jQuery对象。然后从该对象的原型链中选择domInsertMethod,并使用htmlToInsert执行该方法

$(domInsertID)[domInsertMethod](htmlToInsert);
演示:

这是因为
$(domInsertID)
(或任何
$()
)的结果是一个jQuery对象,因此它具有要调用的属性和方法。通常,您使用点符号来访问它们,但括号符号同样有效。括号表示法是动态获取属性/方法的唯一方法(并允许使用无效的标识符字符)

但要小心,因为从技术上讲,任何方法名称都可以提供,因此可以调用。所以这取决于你是否愿意

目前,添加到
$.fn
没有意义,因为您实际上没有使用选择器中的选定元素。使用此设置对我更有意义:

$.appendRecurringHTML = function(domInsertMethod, domInsertID, htmlToInsert) {
    $(domInsertID)[domInsertMethod](htmlToInsert);
};
你会这样称呼它:

$.appendRecurringHTML("after", "#id", "html");
$("selector").appendRecurringHTML("after", "html");
但是,如果要将选定元素用作目标,可以使用:

$.fn.appendRecurringHTML = function(domInsertMethod, htmlToInsert) {
    return this.each(function () {
        $(this)[domInsertMethod](htmlToInsert);
    });
};
把它叫做:

$.appendRecurringHTML("after", "#id", "html");
$("selector").appendRecurringHTML("after", "html");
演示:


它保留链接,并将应用于所有匹配的元素。

只需使用
$(domInsertID)[domInsertMethod](htmlToInsert)。但要小心,因为从技术上讲,任何方法名称都可以提供,因此可以调用。所以这取决于你是否允许它或它not@Ian天才!介意扩展回答吗?我现在正在写:)