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

后端 未结 3 1455
别那么骄傲
别那么骄傲 2020-12-15 12:05

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\'

相关标签:
3条回答
  • 2020-12-15 12:26

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

    $(markup).find("requiredElement").css({ set the properties here });
    
    0 讨论(0)
  • 2020-12-15 12:47

    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');
        }
    });
    
    0 讨论(0)
  • 2020-12-15 12:49

    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.

    0 讨论(0)
提交回复
热议问题