简体   繁体   English

如何使用 jquery ajax 将 css 样式添加到动态加载的代码段

[英]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:- xyz.php正在以以下格式创建一个 html 片段文件:-

<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 :-我在.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?上述方法均无效,但是当我在浏览器中检查元素时,它显示了添加到所需列表元素 (li#content) 的样式。我正在为 div 使用 jscrollpane 这是否会产生问题?

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附带说明一下,我会避免在 HTML 属性上混合单引号和双引号

You can use jQuery .done() method, and pass function there as a callback.您可以使用 jQuery .done()方法,并将函数作为回调传递给那里。 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.是 jScrollPane 防止溢出被隐藏。 Solution i have found out is by setting contentWidth: 0px of the jScrollPane element.我发现的解决方案是通过设置 jScrollPane 元素的contentWidth: 0px

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.正确的方法是使用函数(数据)参数调用 .load,然后将其包装在 Object 中并将其作为纯 HTML 吐出并将其附加到 div 中。 than add any css or any code you like as its now pure html and inserted into the DOM properly.比添加任何 css 或任何您喜欢的代码作为它现在的纯 html 并正确插入到 DOM 中。

     $(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"});*/
 });

}); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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