jQuery: Changing the CSS on an element loaded with ajax?

半腔热情 提交于 2019-11-27 16:32:24

问题


I need to change the position of an element i'm loading with ajax. I want to use .css() to change it but jQuery can't find the element cause it's not being recognized. How do i do to make jQuery "recognize" the element?

I've read about live() and delegate() but i can't get neither one of them to work as i want them to. I'd really appreciate some help!


回答1:


Make the css change in the complete or success function of the ajax call. Assuming you're using load:

$('#el').load(
    url,
    data,
    function(){
        $('#selector').css('position', 'absolute');
    }
);

Alternatively (and easier to give as an example) register an ajaxComplete event

$(document).ajaxComplete(function(){
    if($('#elementID').length != 0) {
        $('#elementID').css('position', 'absolute');
    }
});

This is fired each time an ajax request completes, checks to see if #elementID exists and if so applies the css.




回答2:


If you have to markup in a js variable then you can do it as below.

$(markup).find("requiredElement").css({ set the properties here });



回答3:


If you want to edit it's CSS, you need to place it in the DOM first, then manipulate it.

Example:

$.ajax({
    ...
    success:function(data){
        $('<div/>').appendTo('body').html(data).css('border','3px solid red');
    }
});


来源:https://stackoverflow.com/questions/6866043/jquery-changing-the-css-on-an-element-loaded-with-ajax

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