简体   繁体   English

如何使用jQuery函数存储为对象中的值?

[英]How to use jQuery function stored as a value in an object?

I am a little over my head with understanding why this is not working and how to fix it. 我有点理解为什么这不起作用以及如何解决它。

I have an object created using wp_localize_script() in another file and I'm using it to pass a value to my js file. 我在另一个文件中使用wp_localize_script()创建了一个对象,我正在使用它将值传递给我的js文件。

I am passing other more static values this same way and it is working well, but I have one instance where the value I am passing is a jQuery function that I need to be executed. 我以相同的方式传递其他更多静态值并且它运行良好,但我有一个实例,其中传递的值是我需要执行的jQuery函数。

jQuery(document).ready( function ($) {

    if( wptjCustomInit.opt != "" ) {

        wptjCustomInit.opt;

        console.log(wptjCustomInit.opt); //outputs correct content: $('.table-juice').DataTable();

    }else{

    ...other code...

My goal is for the content of the object to be processed along with the rest of the script as if it had been in the file all along. 我的目标是将对象的内容与脚本的其余部分一起处理,就好像它一直在文件中一样。

I'm guessing I just don't understand something fundamental and I'm not getting to the right scenario in my search attempts. 我猜我只是不理解一些基本的东西而且我没有在我的搜索尝试中找到正确的方案。 I'm grateful for any help! 我很感激任何帮助! (sorry for my ignorance) (对不起我的无知)

If I've understood correctly, it might be as simple as just adding parentheses to the method name: 如果我理解正确,可能就像在方法名称中添加括号一样简单:

wptjCustomInit.opt();

That is the standard way to call a method. 这是调用方法的标准方法。

Even though I am answering my own question, it comes with the help of those who commented on this question. 即使我正在回答我自己的问题,它也会得到那些评论这个问题的人的帮助。

The solution is to use the javascript eval() function. 解决方案是使用javascript eval()函数。 Like this: 像这样:

eval(wptjCustomInit.opt);

From W3Schools about eval() : W3Schools关于eval()

The eval() function evaluates or executes an argument. eval()函数计算或执行参数。

If the argument is an expression, eval() evaluates the expression. 如果参数是表达式,则eval()计算表达式。 If the argument is one or more JavaScript statements, eval() executes the statements. 如果参数是一个或多个JavaScript语句,则eval()执行语句。

I greatly appreciate the help and time spent helping me understand and solve the problem! 我非常感谢帮助我理解和解决问题的帮助和时间!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM