简体   繁体   中英

How can I bind a click event to dynamically created TDs?

I have a function that takes some json data and puts it into a table. I'm trying to bind a click event to certain table elements. In this case the table has two columns 'Drink Name' and 'Drink Type'. I want the two columns to have different events so I'm trying to give them class tags so I can bind the event to a given class.

The lines wrapped in ** are pseudo code for what I'm trying to do. I've tried looking at a bunch of stuff and can't quite figure this out...thanks!!

function totable(data){
                var d = document.getElementById("drinkList");
                d.setAttribute("class","panel panel-default");
                var dd = document.createElement("div");
                dd.setAttribute("class","panel-heading");
                dd.appendChild(document.createTextNode("Drink list"));
                d.appendChild(dd);
                var mytable = document.createElement("table");
                mytable.setAttribute("class","table");
                var thr = document.createElement("tr");
                for(var key in data[0]){
                    var th = document.createElement("th");
                    th.appendChild(document.createTextNode(key));
                    thr.appendChild(th);
                }
                mytable.appendChild(thr);
                for(var i=0;i<data.length;i++){
                    var r = document.createElement("tr");
                    for(var key in data[i]){
                        var td = document.createElement("td");
                        **td.setClassName("drinkEntry");**
                        td.appendChild(document.createTextNode(data[i][key]));
                        r.appendChild(td);
                    }
                    mytable.appendChild(r);
                }
                d.appendChild(mytable);
                **$("#drinkEntry").on("click", viewDrink);**
            }

you can use method .on() with document to bind the event instead directly to the class ( not id ) because the instance doesn't exist already
try this:

$(document).on("click",".drinkEntry", function(){

});

Replace **td.setClassName("drinkEntry");** with $(td).click(viewDrink); .

Try this

$('body').on('click','#drinkEntry',function(){

//Your Codes

});

To bind event to dynamically created items you must use .on() jQuery function.

In your case it should looks like:

$('#drinkEntry').on("click", function () {
    //logic
});

try out

$('body').on('click', 'td.drinkEntry', function() {
    alert("td clicked");
});

JsFiddler Demo

you can also read help full aticle for this : Bind events to dynamically created elements using jQuery

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