将String传递给jQuery函数作为Object

时间:2020-11-30 18:58:54

This might be a stupid question, but I'm trying to pass in a string of settings I've constructed in the following format:

这可能是一个愚蠢的问题,但我试图传递一系列我用以下格式构建的设置:

"setting1" : "value", "setting2" : "value", "setting3" : "value"

The above is saved to a string named args. Nothing special, but I'm wanting to pass it in as an argument to a function.

以上内容保存为名为args的字符串。没什么特别的,但是我想把它作为参数传递给函数。

$('#element').functionName({ args });

I'm not sure what I'm missed here.... Thanks!

我不确定我在这里错过了什么....谢谢!

2 个解决方案

#1


3  

If you really have a string such as this:

如果你真的有这样的字符串:

'"setting1" : "value", "setting2" : "value", "setting3" : "value"'

You can parse it using JSON.parse and get an object out of it like so:

你可以使用JSON.parse解析它并从中获取一个对象,如下所示:

var args = JSON.parse( "{" + str + "}" );
$('#element').functionName(o);

But in reality you probably want to just create such an object instead of a string from the start, e.g.:

但实际上你可能只想从一开始就创建这样一个对象而不是一个字符串,例如:

var args = {"setting1" : "value", "setting2" : "value", "setting3" : "value"};
$('#element').functionName(args);

#2


1  

There is no such thing as a stupid question. Try:

没有一个愚蠢的问题。尝试:

var args = JSON.parse("{'setting1' : 'value', ...}");

And then pass the "args" variable into your function.

然后将“args”变量传递给您的函数。

#1


3  

If you really have a string such as this:

如果你真的有这样的字符串:

'"setting1" : "value", "setting2" : "value", "setting3" : "value"'

You can parse it using JSON.parse and get an object out of it like so:

你可以使用JSON.parse解析它并从中获取一个对象,如下所示:

var args = JSON.parse( "{" + str + "}" );
$('#element').functionName(o);

But in reality you probably want to just create such an object instead of a string from the start, e.g.:

但实际上你可能只想从一开始就创建这样一个对象而不是一个字符串,例如:

var args = {"setting1" : "value", "setting2" : "value", "setting3" : "value"};
$('#element').functionName(args);

#2


1  

There is no such thing as a stupid question. Try:

没有一个愚蠢的问题。尝试:

var args = JSON.parse("{'setting1' : 'value', ...}");

And then pass the "args" variable into your function.

然后将“args”变量传递给您的函数。

相关文章