This question already has an answer here:
call variable jQuery function
(1个答案)
3年前关闭。
我只是希望,可能我不可能做什么。如果没有,那没有问题,我将编写一个类。我只是想避免这种情况。
当然,我试图在网上寻找答案。我在SO和jQuery论坛上找到了一些东西。如this或this或this。
但是我想以不同的方式做到这一点:
我想直接调用它,并且我不想使用eval!
我想做这样的事情
我得到这个:
那么有没有办法做到这一点?
(1个答案)
3年前关闭。
我只是希望,可能我不可能做什么。如果没有,那没有问题,我将编写一个类。我只是想避免这种情况。
当然,我试图在网上寻找答案。我在SO和jQuery论坛上找到了一些东西。如this或this或this。
但是我想以不同的方式做到这一点:
我想直接调用它,并且我不想使用eval!
我想做这样的事情
var target = '#id';
var method = 'removeClass';
var className = 'classToShow';
$(taget).method(className);
我得到这个:
TypeError: $(...).method is not a function
[Learn More]
那么有没有办法做到这一点?
最佳答案
由于jQuery
(因此是$
变量)引用一个对象,因此可以使用方括号表示法,如下所示:
$(target)[method](className);
var target = '#id';
var method = 'removeClass';
var className = 'classToShow';
$(target)[method](className);
.classToShow {
color: red; /* this colour will be removed */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id" class="classToShow">Foo bar</div>
关于jquery - 直接从变量名调用jQuery函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38590068/