简体   繁体   中英

jQuery - on load of element with ajax

I searched for some time but could not find a working solution for my problem (sorry if I searched wrongly)... I would like to have the equivalent of the following function for an element loaded with ajax:

$(document).ready(function() {
    $('.div-modal-text').css("background-color","red");
});

Therefore I am using the following code:

  $('#parent_id').on('action', '#id or class to be born', function to be performed() );

In my example the parent-child structure is: #projectModals (div whose content is dynamically loaded)>...>.div-project-description>.div-modal-text

This translates into the following code in my example:

  $('#projectModals').on('load', '.div-project-description', function() {  
      $(this).find('.div-modal-text').each(function() { 
           $(this).css("background-color","red");

    });
  });

I know 'load' does not work with .on(), but I tried different alternatives and I could not find anything working.

Thanks for your help!

EDIT : Here is my (simplified) HTML code:

    <div id="projectModals"></div>

content loaded in #projectModals with Ajax:

      <div class="row">
        <div class="div-project-idcard">          
            column 1, don't bother too much about this column            
        </div>
        <div class="div-project-description"> 
          <div id="summary" class="div-modal-text">
            Column2, text 1               
          </div>
          <div id="purpose"  class="div-modal-text"">
            Column2, text 2
          </div>
          <div id="reforestation"  class="div-modal-text">
            Column2, text 3
          </div>
          <div id="certification"  class="div-modal-text">
            Column2, text 4
          </div>
        </div>          
      </div>

If you're waiting for it to be loaded via ajax, consider using $(window).ajaxSuccess() instead:

  $(window).ajaxSuccess(function(){
    $('#projectModals .div-project-description .div-modal-text').each(function() { 
        $(this).css("background-color","red");
    });
  });

for what I understand, you want to change some background color after an ajax has been executed.

I think it's best to make the operation in the ajax success

$.ajax({
    url: "some url",
    data: {some data},
    success: onAjaxSuccess,
});

and then;

function onAjaxSuccess(data){
    //.. do things with data
    var toExecute = $('#projectModals .div-project-description');
    toExecute.find('.div-modal-text').each(function() { 
           $(this).css("background-color","red");
    });
}

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