简体   繁体   中英

how to apply CSS styles in current document recieved from AJAX request?

I have an AJAX request, that returns a few CSS IDs, like:

#id1{something:something}
#id2{something:something}
#id3{something:something}
...etc ect

Is there any way I could add these ID's to the current document (the document that made the AJAX request) using Javascript/JQuery?

I make the AJAX request, using JQuery and JSON variables, if that helps...

Rather than using AJAX to fetch the CSS and then worry about inserting it into the document, you could just dynamically add a <link> tag to the document:

<link rel="stylesheet" type="text/css" href="..." />

The href should then include the required parameters needed by the CGI script.

var url = "......"; // including parameters

var script = $('<link>', {
   rel: 'stylesheet',
   type: 'text/css',
   href: url
}).appendTo(document.head);

The browser will then automatically trigger the loading of the new CSS file. If you wish to catch the completion of that you should be able to add a .load() handler.

您可以创建/编辑<style>标记并将您的内容放在此处,浏览器会识别并应用它。

Why not have your AJAX function return a JSON object like

var data = {id1: {something: something}, id2: {something: something}, id3: {}}

and apply that using

$.each(data, function(index, item) {
    $('#' + index).css(item);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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