简体   繁体   中英

onclick funtion when I add a button in ajax

I want to use AJAX to get information. If succeeds, I want to append the data into a table. Also, in each tr , I add a button, and I want to trigger an event if I click the button. Thus, I just append a button with an onclick function into the table. While, the onclick function does not work. Does anyone know why? and how I can reach my goal?

Here is the code:

 $.ajax({
    url: 'https://api.instagram.com/v1/tags/'+tag+'/media/recent',
    type: "GET",
    dataType: "jsonp",
    cache: false,
    data:{
        access_token: access_token,
        count: count
    },
    success: function(data){
       for(var x in data.data){
         var html="";
         tdHtml +="<tr><td>"+"<a href='"+data.data[x].link+"'><img src='"+data.data[x].images.thumbnail.url+"'></img></a>"+"</td>"+ 
                    "<td class='text-center'>"+data.data[x].caption.from.username+"</td>"+
                    "<td class='text-center'>"+data.data[x].likes.count+"</td>"+
                    "<td>"+create_time+"</td>"+
                    "<td>"+tags+"</td>"+
                    "<td>"+"<button id='addUsers' class='btn btn-primary btn-xs' onclick='addUsers()'>Add Users to a Group</button>"+"</td></tr>";
     }
  }
});

EDIT: Actually, the onclick function is like this:

 "<td>"+"<button id='addUsers' class='btn btn-primary btn-xs' onclick='addUsers('"+data.data[x].caption.from.username+"')'>Add Users to a Group</button>"+"</td></tr>";)'>Add Users to a Group</button>"+"</td></tr>";

Once I click the button, I can do something with the data's username I get via AJAX. However, even if I write simply, it cannot work. For example:

function addUsers(name){
  console.log(name);
}

The name cannot be consoled. There is an undefined error, or other error happened.

So, the goal for me is to get response from developer(done), append it to a table in html(done), and click a button(which was append formerly) to do more things with the appended information. Here, I want to add the name into a certain list.

我认为按钮导致回发,因此再次重新加载页面尝试使用此按钮代替按钮

 <input type='button' id='addUsers' class='btn btn-primary btn-xs' onclick='addUsers()' value='Add Users to a Group' /> 

Let me describe another way to do this and avoid duplicated event attributes:

  1. Invent a class. For instance, let's call it simply addUsersButton .

  2. Add this class to your button while dynamically creating it:

     tdHtml += /* ... other code here */ + "<button class='btn btn-primary btn-xs addUsersButton'>Add Users to a Group</button>"; 

    Note that there is no onclick attribute.

  3. Now, using event delegation , define the following handler:

     $(document).on('click', 'addUsersButton', function() { var username = $(this).parent().find('td:eq(1)').text(); addUsers(username); }); 

    Now, all of your addUsersButtons will trigger this event whether they are dynamically generated or not.

    $(this).parent().find('td:eq(1)').text() will work because you store data.data[x].caption.from.username in the second cell of the current row. However, it is not a best idea to use this approach. You can declare some kind of data-username attribute and access it using $(selector).data('username') .

You have messed up your quotes:

"<td>"+"<button id='addUsers' class='btn btn-primary btn-xs' " +
  "onclick='addUsers(\""+
  data.data[x].caption.from.username+
  "\")'>Add Users to a Group</button>"+
  "</td></tr>";

Note \\" wrapping the parameter for addUsers .

I suggest you use event delegation, and here is the sample:

html:

<button id="addContentBtn"> add content to table</button>
<table id="testTbl"></table>

js

$(document).ready(function() {

   ("#addContentBtn").click(function(){
        var str="<tr><td>1</td><td><button>button</button></td></tr>" +
         "<tr><td>2</td><td><button>button</button></td></tr>" ;
        $(str).appendTo("#testTbl");
   })

   //this is event delegation
   $("#testTbl").on("click","button",function(){
                alert("clicked");
   })

});

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