Assigning click event to dynamically added buttons

2019-02-03 21:08发布

问题:

I am creating some buttons dynamically and assigning them IDs.

When ever someone clicks that button I want to collect the ID and from there perform some task.

Here's my work in progress

$(document).ready(function() {
    $('input:button').addClass("btnClass");
    fillData();
    $('#btnGet').click(function() {
        fillData();
    });
    function fillData() {
        $.ajax({
            type: "Post",
            url: "../Linq/myService.asmx/getStudent",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                //var nMsg = (typeof msg.d) == 'string' ? eval('(' + msg.d + ')') : msg.d;
                var t = "<table width='80%' id='resTab'> <tr>" +
                      "<td colspan='5' style='text-align:center'><font size='3'><strong>Your Search Result......</strong></font></td></tr> <tr><td style='text-align:left' colspan='5'><hr></td></tr> "
                      + " <tr><td style='text-align:center'>Student ID</td><td style='text-align:center'>Student Name</td><td style='text-align:center'>Student Course</td><td style='text-align:center'>Student USN</td></tr>"
                      + " <tr><td style='text-align:left' colspan='5'><hr><br></td></tr> ";
                $.each(msg.d, function(index, item) {
                    t = t + " <tr><td style='text-align:center'>" + item.studId + "</td><td style='text-align:center'>" + item.studName + "</td><td style='text-align:center'>" + item.studCourse + "</td><td style='text-align:center'>" + item.studUsn + "</td><td><input type='button' ID='btn" + item.studId + "' value='Delete' onClick='onButtonClick()'/></td></tr>";
                    t = t + " <tr><td style='text-align:left' colspan='5'><hr></td></tr> ";
                });
                t = t + " </table> ";
                $("#stdData").html(t);
            },
            error: function(msg) { }
        });
    }


function onButtonClick() {
    var btnId = $(this).val();
    alert(btnId);
}

回答1:

Just add a class name of new-button to the buttons you're creating and add a click handler afterwards.

So replace this code

<input type='button' ID='btn"

with this

<input type='button' class="new-button" ID='btn"

You can remove the onButtonClick() from the onclick event and replace

function onButtonClick() {
    var btnId = $(this).val();
    alert(btnId);
}

with

$(".new-button").live("click", function() {
    var buttonId = $(this).attr("id");
    alert(buttonId);
});


回答2:

I am not sure I understand exactly your problem, but you can try writing

var btnId = $(this).attr('id');

instead of

var btnId = $(this).val();

this will give you the id attribute of the button clicked and not the value of the form element.

I hope this will help you

Jerome Wagner



回答3:

If you are dynamically adding buttons, think about using ".live()". Whenever the specified event happens, it follows the html elements up the tree until it is handled. This is more efficient if you have a lot of elements also because the event isn't assigned to the element itself. You need to assign a class or something to the buttons to identify them, let's say 'dynamicButton', so change this:

<input type='button' ID='btn" + item.studId + 
"' value='Delete' onClick='onButtonClick()'/>

to this:

<input type='button' ID='btn" + item.studId + 
"' value='Delete' class="dynamicButton"/>

And you can listen to events with this code:

$('input.dynamicButton').live('click', function (event) {
        alert($(this).attr('id'));
    });

This one handler will be called anytime a button with the class 'dynamicButton' is clicked no matter how it is added to the page.



回答4:

When ever someone ll click that button I want to collect the ID and from there I ll do some task upon that.............

Try removing onclick attribute from this line:

t = t + " <tr><td style='text-align:center'>" + item.studId + "</td><td style='text-align:center'>" + item.studName + "</td><td style='text-align:center'>" + item.studCourse + "</td><td style='text-align:center'>" + item.studUsn + "</td><td><input type='button' ID='btn" + item.studId + "' value='Delete' onClick='onButtonClick()'/></td></tr>";

Making it:

t = t + " <tr><td style='text-align:center'>" + item.studId + "</td><td style='text-align:center'>" + item.studName + "</td><td style='text-align:center'>" + item.studCourse + "</td><td style='text-align:center'>" + item.studUsn + "</td><td><input type='button' ID='btn" + item.studId + "' value='Delete'/></td></tr>";

And now you can use jQuery's live method (since your button is generated dynamically) to do the trick when this button is clicked like this:

$(function(){
  $('#btn').live('click', function(){
     var btnId = $(this).attr('id');
     alert(btnId);
  });
});

Note:

To get id attribute, you can use attr method like shown above eg: $(this).attr('id') not val (which is used to get the value of an input element) like your in your code.



回答5:

I did this using delegate(). In my case, a PHP script generates the content of a page from a MySQL database. To each element, a button is added (clicking these buttons can remove the respective element from the database). The removal is handled by another PHP script which these buttons activate, so a click event is attached to each button like this:

$('.items').delegate('[type="button"]', 'click', remove_item);

where the buttons are part of the items class and remove_item is the callback for the removal.