The content loaded by ajax does not take the styles of the page

岁酱吖の 提交于 2021-02-10 14:38:59

问题


With ajax I am bringing content to upload my website with information. What the page does is load everything normally first, then execute the corresponding ajax, but when loading the ajax and placing the appropriate information, this information does not apply the styles of the web page. Here is an example of how my code would be:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>

    <!-- Styles that you do not recognize -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div id="content" class="div-short"></div>
    <script src="js/jquery.js"></script>
    <script>
        $.ajax({
            type: 'POST',
            url: "http://localhost:8000/api/pag/5",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data){
                // Dynamic information
                $('#id').html(data);
            }
        });
    </script>
</body>
</html>

If someone has some kind of solution or how it can be done, it is very useful for me. Thank you


回答1:


Example Snippet

In the example below...

  • assume that const data is being returned from your ajax call
  • ignore everything except the jQuery, since it's all just to show that styles come through-- the point is to focus on how the HTML is generated
  • I'm aware I didn't use your exact code and IDs to create this snippet. That doesn't matter-- what matters is the educational takeaway you can get from seeing the data flowing.

const data = '[{"species": "dog", "breed": "Husky", "name": "Kenna"},{"species": "cat", "breed": "Siamese", "name": "Jeff"},{"species": "dog", "breed": "Doberman", "name": "Bella"}]';

let parsed_data = jQuery.parseJSON(data);
var html = "";

$.each(parsed_data, function(key, value) {
  html += '<div class="card"><h3>' + value.name + '</h3><p>Species: ' + value.species + '</p><p>Breed: ' + value.breed + '</p></div>';
});

$("#container").html(html);
.card {
  margin: 20px;
  padding: 20px;
  background-color: #EEE;
  font-family: "Arial", sans-serif;
  cursor: default;
}

.card > h3 {
  color: blue;
  cursor: pointer;
}

.card > h3:hover {
  text-decoration: underline;
}

.card > p {
  color: #555;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="container"></div>

Explanation

Notice how the first thing I did with the data was run jQuery.parseJSON() on it. This takes the result from a string representation to a javascript object.

I then loop through the javascript object with $.each. I access the variables with the funcParam.keyName format (e.g. the first access value.name).

I finally included the generated HTML in a variable, and then used .html() to add it to my container after the $.each (which is faster than using .append() on each iteration of the loop).

See below where the HTML generation code would be placed:

$.ajax({
   type: 'POST',
   url: "http://localhost:8000/api/pag/5",
   contentType: "application/json; charset=utf-8",
   dataType: "json",
   success: function(data){
      // run your HTML generation code (like my Snippet example) HERE
   }
});



回答2:


If you deal with changes in DOM (via AJAX), you need to understand, that addClass() or something like toggleClass() will work only for currently present objects. All newly appended or loaded items will not be styled, unless they are chіldren of parents which have CSS for children. Loading external CSS sometimes is a hassle.

Good practice in my case came to use variables in CSS. Examples of usage: you need to change skin of website/webapp, make a nightmode/daymode or just to style loaded elements correctly.

As example, let's take initial color of text and background in variables:

/* CSS for day mode */
:root {
  --textcolor: #333;
  --bgcolor: #fff;
} 

JS allows you to change the variables in CSS (along with saving that information), here is handy JS snippet from Ciaran O'Kelly for manipulating with CSS variables:

/** 
 * Gets and sets css vars
 * get a css var:
 * cv('bgcolor') // Returns #ccc
 * set a css var:
 * cv('bgcolor','#f00') // Sets and returns #f00
*/
function cv(n,v) {
    if(n[0]!='-') n = '--'+n //allow passing with or without --
    if(v) document.documentElement.style.setProperty(n,v)
    return getComputedStyle(document.documentElement).getPropertyValue(n);
}

And finally, user function to change UI. Styles will be aplicable to all present and yet not loaded elements in DOM:

function change_skin() {
    if($("#sk").text() == 'Night') {
        
        // Night mode skin
        cv('bgcolor','#666')
        cv('textcolor','#eee')
        
        // Change label
        $("#sk").text('Day')
        
    } else {

        // Day mode
        cv('bgcolor','#fff')
        cv('textcolor','#333')

        // Change label
        $("#sk").text('Night')

    }
}



回答3:


i think you need to format your data in html... example

$('#id').append("<span class='yourclass'>"+ data.name +"</span>");

that way you make thediv with all the data and styles you need and then append it to your div #id




回答4:


after get response add simple html with class for example

$('#id').append('<p class="test">test</p>');

and in the head add the following line

<style>
.test { font-size: 50px; }
</style>

if your "p" get the given style that's means your problem with "data" variable



来源:https://stackoverflow.com/questions/56760072/the-content-loaded-by-ajax-does-not-take-the-styles-of-the-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!