1

My code uses a jQuery plugin that inserts some HTML code.

I have the option to change the inserting method, by setting them via variable.

The variable is called:

var options = {insert: 'append'};

I don't want to do that with an if condition, like that:

if(options.insert === 'append') {
 $('#foobar').append(htmlcode);
}else if (options.insert === 'prepend'){
 $('#foobar').prepend(htmlcode);

... and so on.

Is there any solution to insert the html code with a given varibale method?

4

1 回答 1

6

因为 jQuery 构造是一个对象,所以您可以使用括号表示法来访问函数。尝试这个:

$('#foobar')[options.insert](htmlcode);

只要options.insert匹配一个函数的名称,它就可以工作。

示例小提琴

于 2013-11-01T13:24:59.867 回答