简体   繁体   中英

how to add css style to dynamically loaded snippet using jquery ajax

var loc="/blah/blaah.html"

$.ajax({

   url: 'xyz.php',
   type: 'POST',
   success:function()
           {
              $('#mydiv').load(loc);
           }
 )}

xyz.php is creating a html snippet file in the fllowing format:-

<li id='messagebody'> <ul> <li><img src="abc.jpg" width="42" height="42"></li> <li id='content'>asdjkshadjhasdjjasdhjas</li> <li>21 Aug 20013</li> </ul> </li>

i have tried callback in .load :-

$('#mydiv').load(loc,
             function(){
                      $('li#content').css({'overflow':'hidden'});
            });

and also tried by generating the snippet with style attribute:-

<li id='messagebody'> <ul> <li><img src="abc.jpg" width="42" height="42"></li> <li id='content' style='overflow:hidden;'>asdjkshadjhasdjjasdhjas</li> <li>21 Aug 20013</li> </ul> </li>

none of the above method is working but when i inspect elements in browser it shows the style added to the desired list element (li#content).I am using jscrollpane for the div is this creating problem?

Try this

$.ajax({
    url:  'xyz.php',
    method: 'post',
    success: function(response)
    {
        $('#mydiv').append(response);
    }
}).done(function(){
   $('#content').css('overflow', 'hidden');

});

On a side note I'd avoid mixing single and double quotes on HTML attributes

You can use jQuery .done() method, and pass function there as a callback. And in that function add a class to an element. It is better than adding inline styles.

it was the jScrollPane which was preventing the overflow from being hidden. Solution i have found out is by setting contentWidth: 0px of the jScrollPane element.

The correct way is to call the .load with a Function (data) parameter, then wrap it in Object and spit it back out as plain HTML and append it the div. than add any css or any code you like as its now pure html and inserted into the DOM properly.

     $(document).ready(function(){

$('#template').load('http://localhost/site root/site folder/index.html 
 section#togo', function(template) {
 var obj = $(this).find('section#togo'), html = obj.html(); 
 $(this).append($('<div>').text(html)); 
 $('div[id^="menu"]').css({display: "block"}); 
/*$('#menu1').css({display: "block"});*/
 });

});

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