jQuery 从字符串调用函数 [英] jQuery call function from a string

查看:16
本文介绍了jQuery 从字符串调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用字符串来调用函数?

Is it possible to call a function by using the strings ?

(即)我有一个变量 var target = 'next';.使用这个字符串,我想调用 jquery 方法 next() .我应该使用 target + '()' (这有点愚蠢)来调用 next() 吗?

(i.e) I have a variable var target = 'next';. Using this string I want to call the jquery method next() . Should i use target + '()' (this is bit foolish) to call next() ?

我知道可以使用 conditional 语句来完成.既然是从用户那里得到的字符串,但是很难用条件语句来处理.

I know it can be done using conditional statements. Since it is a string got from users, but it is difficult to use conditional statements for all that.

在我的 jQuery 插件中,用户将传递值 prevsiblings 等作为选项,以便执行相应的 jQuery 方法.

In my jQuery plugin, users will pass the value prev, siblings etc as options, so that the respective jQuery methods will be executed.

我该如何实现?

推荐答案

您可以使用 括号表示法 使用包含标识符的字符串访问成员:

You can use the bracket notation to access the member with a string containing the identifier:

var target = 'next';
$("foobar")[target]();    // identical to $("foobar").next()

这篇关于jQuery 从字符串调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆