1

I'm not sure what to do here. . . I'm trying not to ask a duplicate question, but after searching I'm still stuck.

I am using wordpress AJAX with 2 functions back to back.

The first jQuery function makes an AJAX request which generates a ul, with an a in each li. Each anchor gets a class="ajax-link", and also gets data-value="<?php echo $var; ?>.

The anchor in the FIRST li gets class="ajax-link thefirstcn".

Immediately after this list is generated and written to the page, this function fires (there's more to it than this, but I'm shortening it):

function select_on_load() {
  var first = $(".thefirstcn").attr('data-value');

  alert(first);
}

No matter what I try, all I get is undefined when trying to fetch the information. I've tried assigning the value to a regular "id" tag, that isn't working either.

I'm sure it's got something to do with the fact that the element was just created, I just need to know how to go about getting it!! Thanks again

rnevius
  • 26,578
  • 10
  • 58
  • 86
drumichael611
  • 151
  • 3
  • 9
  • 1
    jQuery is only aware of the elements in the page at the time that it runs, so new elements added to the DOM are unrecognized by jQuery. To combat that use [event delegation](http://learn.jquery.com/events/event-delegation/), bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. Many people use `document` as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally [you should delegate to the nearest parent that exists at the time of page load.](http://stackoverflow.com/a/12824698/1011527) – Jay Blanchard Oct 16 '15 at 21:35

1 Answers1

1

If you have some functions that run on load $(document).ready.. which you depend upon to pull your id's for instance and you then modify the dom using ajax after it has loaded it wont pick them up.

So you need to recall those functions after you modify the dom (call your ajax) rip everything out of your $(document).ready or self executing function which runs onload and put it into a named function:

    var myOnload = function(){
        ... your id fetching code here..
    }

    $(document).ready(function () {
       myOnload();
    });

then use the ajax.complete method to load them again...

   $.ajax(...
    .done(function(data){
      ...
     })
    .complete(function(){
        myOnload();
    })
   });
futureweb
  • 442
  • 4
  • 12