调用用变量标识的jQuery库函数

时间:2013-06-06 13:39:33

标签: javascript jquery oop function variables

我使用jQuery函数构建重复的html。

我想通过$.append()$.before()$.after()等方式为我的功能提供更多灵活性。

目前,我做了类似

的事情
$.fn.appendRecurringHTML = function(domInsertMethod, domInsertID, htmlToInsert) {
    if(domInsertMethod == 'append'){
        $(domInsertID).append(htmlToInsert);
    }
    else if(domInsertMethod == 'before'){
        $(domInsertID).before( ...
}

但我更喜欢(伪)

$.fn.appendRecurringHTML = function(domInsertMethod, domInsertID, htmlToInsert) {
    $(domInsertID).window[domInsertMethod](htmlToInsert);
}

但这对我不起作用。

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

2 个答案:

答案 0 :(得分:2)

只需使用

$(domInsertID)[domInsertMethod](htmlToInsert);

DEMO: http://jsfiddle.net/UZKLY/

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

但要小心,因为从技术上讲,可以提供任何方法名称,因此可以调用。所以,如果你想允许或不允许,这取决于你。

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

$.appendRecurringHTML = function(domInsertMethod, domInsertID, htmlToInsert) {
    $(domInsertID)[domInsertMethod](htmlToInsert);
};

你会这样称呼:

$.appendRecurringHTML("after", "#id", "html");

但是如果你想使用所选元素作为目标,你可以使用:

$.fn.appendRecurringHTML = function(domInsertMethod, htmlToInsert) {
    return this.each(function () {
        $(this)[domInsertMethod](htmlToInsert);
    });
};

并称之为:

$("selector").appendRecurringHTML("after", "html");

DEMO: http://jsfiddle.net/UZKLY/1/

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

答案 1 :(得分:1)

试试这个:

$(domInsertID)[domInsertMethod](htmlToInsert);

此方法首先使用 domInsertID 创建jQuery对象。然后从该对象的原型链中选择 domInsertMethod 并使用 htmlToInsert 执行该方法。