Using jquery to target data tags within json via ajax -


i've got simple ajax call returning json working i'm struggling select elements jquery afterwards. this because of way loaded ajax?

at stage i'm trying alert contents of 1 of data elements 'data-votes'

<div id="list-latest" class="pagelist"></div> <script>  $(function ()    {    $.ajax({                                            url: 'http://example.com/go.php',                        data: "",                              datatype: 'json',                        success: function(data)                  {          var $grouplist = $('#list-latest');          $.each(data, function() {             $('<div class="tile-item"><a href="javascript:void(0);" onclick="alertme();" class="allinfo" data-votes="' + this.votes + '" data-views="' + this.views '" >link</a></div>').appendto($grouplist);           });        }        });       });  

<script type='text/javascript'>   function alertme(){     alert($(this).attr("#data-votes"));   } </script> 

is how i'm trying select (this) ? @ moment returns 'undefined'

thanks

the issue because reference of this in alertme() function window, not element raised click event. need pass reference parameter in function. note syntax retrieve data attribute off. try this:

$('<div class="tile-item"><a href="javascript:void(0);" onclick="alertme(this);" class="allinfo" data-votes="' + this.votes + '" data-views="' + this.views '" >link</a></div>').appendto($grouplist); 
function alertme(el){    alert($(el).data("votes")); } 

it should noted it's better practice hook events using javascript. in case you'd need delegated event handler elements in question appended dom dynamically after load. method mean this reference within handler would refer element raised event. try this:

$(function() {     $.ajax({                                               url: 'http://example.com/go.php',                           data: "",                                 datatype: 'json',                           success: function(data) {             var $grouplist = $('#list-latest');             $.each(data, function() {                 $('<div class="tile-item"><a href="#" class="allinfo" data-votes="' + this.votes + '" data-views="' + this.views '">link</a></div>').appendto($grouplist);             });         });     }      $grouplist.on('click', '.allinfo', function(e) {         e.preventdefault();         alert($(this).data("votes"));     }); }); 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -