简体   繁体   中英

storing id into variable upon clicking after calling AJAX

I tried using an onClick within the <a> tag but it doesn't work. I'm trying to capture 777 into a variable that way I can use it later in the code. I was wanting to click on the image then it display an alert box that way I know that its working, but its not working.

$(function() {
    $.ajax({  
      async: false,    
      cache: false,  
      dataType: 'json',  
      url: 'http://www.getitfree.us/api/posts.json?filter=popular&limit=2',  
      type: "get",  
      success: function(json) {  
        var arr = ['51ae281f1521021885573121', '51b7af297665ebc546c39a34'];  
        for (var i = 0; i < arr.length; i++) {  
            $("#output").append("<div>" + "<a href='./next_page.html' target='_blank' id='777' onClick='Click(this.id)'>" + "<img class='img-responsive' alt='advertisement image' src='" + json.data[arr[i]].images['0'] + "'>" + "</a>" + "<p class='adjust_pTitle'>" + json.data[arr[i]].title + "</p>" + "</div>");
        }  
      },  
      error: function(json) {  
          throw new error();  
      }  
    })  
  });  

  function Click() {  
     alert("clicked");    
  };

Try giving a class, eg .anchor to the appended element and use the on() method to listen to the click event:

 $("#output").append("<div>" + "<a href='./next_page.html' class='anchor' target='_blank' id='777'>" + "<img class='img-responsive' alt='advertisement image' src=''>" + "</a>" + "<p class='adjust_pTitle'>Title</p>" + "</div>"); $(document).on('click', '.anchor', function(e) { e.preventDefault(); alert($(this).attr("id")); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="output"></div> 

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