问题描述
是否可以编写一个html属性来存储javascript函数的名称,然后提取val()并执行该函数?示例:
Is it possible to write an html attribute that will store the name of a javascript function and then extract that val() and execute that function? Example:
<button id="example" data-function-name="showAllElements()">
然后是js / jq
and then in js/jq
fn = $('#example').data('function-name');
fn;
推荐答案
你可以,是的。你应该是否完全是另一个问题,答案几乎肯定是不(就执行字符串而言;就下面显示的替代方案而言,有时它很有用)。
You can, yes. Whether you should is another question entirely, to which the answer is almost certainly "no" (in terms of executing the string; in terms of the alternative shown below, there are times it's useful).
你评估那段代码的方式(你拥有的不是只是一个函数名,因为()
)将使用可怕的 eval
:
The way you'd evaluate that snippet of code (what you have isn't just a function name, because of the ()
) would be to use the dreaded eval
:
eval(fn);
几乎总是比使用 eval
。 (见下文。)
There's almost always a better option than using eval
. (See below.)
eval
例如:
$("#example").on("click", function() {
var fn = $("#example").attr("data-function-name");
eval(fn);
});
function showAllElements() {
alert("showAllElements was called");
}
<button type="button" id="example" data-function-name="showAllElements()">Click Me</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
One 更好的选项是将函数引用存储为对象的属性,然后使用括号表示法根据函数名称获取函数引用:
One of the better options is to store your function references as properties on an object, and then use brackets notation to get the function reference based on the function name:
示例:
var functions = {
showAllElements: function() {
alert("showAllElements was called");
}
};
$("#example").on("click", function() {
var fn = $("#example").attr("data-function-name");
functions[fn]();
});
<button type="button" id="example" data-function-name="showAllElements">Click Me</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
请注意那里,我只是存储函数名,而不是任意代码。
Note that there, I'm just storing the function name, not arbitrary code.
更新:参见,如果您的函数嵌套在对象中,则可以通过巧妙的方式处理它,例如 mumble.foo.doSomething
,使用 reduce
。 ( reduce
是ES5功能,但它是可填充的。)
Update: See canon's answer for a clever way to handle it if you have your functions nested inside an object, e.g. mumble.foo.doSomething
, using reduce
. (reduce
is an ES5 feature, but it's polyfillable.)
旁注:除非您执行的操作不仅仅是检索数据 - *
属性的值,否则请勿使用数据
,使用 attr
。 data
初始化元素的数据缓存,读入该元素的所有数据 - *
属性,并复制他们要缓存。如果你没有使用它,没有理由这样做。您使用 data
访问 data - *
属性的想法是一种常见的误解。
Side note: Unless you're doing something more than just retrieving the value of a data-*
attribute, don't use data
, use attr
. data
initializes a data cache for the element, reads in all of the data-*
attributes for that element, and copies them to cache. If you're not using it, there's no reason to do that. The idea that you use data
to access data-*
attributes is a common misconception.
这篇关于你可以将javascript函数名称设置为html属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!