javascript 如何将 json 数据发送到 jQuery.css()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5593293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send json data to jQuery.css()
提问by grizwako
I want to send json formatted data to jQuery.css() function, and i dont know how to do that. Later on, i will send more properties, this is just example of my problem.
我想将 json 格式的数据发送到 jQuery.css() 函数,但我不知道该怎么做。稍后,我将发送更多属性,这只是我的问题的示例。
//Sorry, this var x is actually string that i get when i print my json string
var x = {"transform":"rotate(30deg)","-o-transform":"rotate(30deg)"}
//If i try to do something like this wont work
$("#mainImage").css(x);
//but following works
$("#mainImage").css({"transform":"rotate(30deg)","-o-transform":"rotate(30deg)"})
It probably has to do something that jquery accepts .css( map )
A map of property-value pairs to set.
它可能必须做一些让 jquery 接受.css( map )
要设置的属性-值对映射的事情。
And i am trying to send single text string, can i somehow convert json to map ?
我正在尝试发送单个文本字符串,我可以以某种方式将 json 转换为 map 吗?
@Pekka Yes, i am sure that $("#mainImage").css(x);
doesnt work.
@Pekka 是的,我确定那$("#mainImage").css(x);
行不通。
@Felix That is what i get by calling json = JSON.stringify(data);
sorry if it not json data, i am js newbie..
@Felixjson = JSON.stringify(data);
如果不是json数据,这就是我通过调用抱歉得到的结果,我是js新手..
采纳答案by cem
You should parse not stringifyJSON before. I tried this one It's works.
您应该先解析而不是字符串化JSON。我试过这个它是有效的。
var json = '{ "display": "none" }';
var cssObject = JSON.parse(json);
$("#mainImage").css(cssObject);
回答by Karol
I've just tried with this code:
我刚刚试过这个代码:
$(document).ready(function() {
var x = {"background-color": "yellow"};
$('body').css(x);
});
And basically it works. So the problem can be in sth totally different. Maybe your img element is not there?
基本上它有效。所以问题可能完全不同。也许你的 img 元素不存在?
回答by danidacar
var cssObj = { 'background-color' : '#ddd', 'font-weight' : '', 'color' : 'red', "transform":"rotate(30deg)", "-o-transform":"rotate(30deg)", "-webkit-transform":"rotate(30deg)" } $("#mainImage").css(cssObj);