How to send json data in jQuery.css ()

I want to send json-formatted data to jQuery.css () function, and I don't know how to do it. I will post more properties later, this is just an example of my problem.

//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)"}) 

Maybe something that jquery accepts .css( map )
A map of the pairs of property values ​​to set.

And I'm trying to send a single text string, can I somehow convert json to display?

@Pekka Yes, I'm sure $("#mainImage").css(x); does not work.

@Felix This is what I get by calling json = JSON.stringify(data); sorry if this is not json data i'm new to js ..

+4
source share
3 answers

You have to parse so as not to give JSON before. I have tried this. He works.

 var json = '{ "display": "none" }'; var cssObject = JSON.parse(json); $("#mainImage").css(cssObject); 
+3
source

I just tried with this code:

 $(document).ready(function() { var x = {"background-color": "yellow"}; $('body').css(x); }); 

And basically it works. Thus, the problem may be completely different. Maybe your img element is missing?

+1
source

http://jsfiddle.net/A4azg/

 var cssObj = {
       'background-color': '#ddd',
       'font-weight': '',
       'color': 'red',
       "transform": "rotate (30deg)",
       "-o-transform": "rotate (30deg)",
       "-webkit-transform": "rotate (30deg)"
     }
 $ ("# mainImage"). css (cssObj);

0
source

Source: https://habr.com/ru/post/1347221/


All Articles