最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to put an onclick event for a HTML table row created dynamically through java script.? - Stack Overflow

programmeradmin1浏览0评论

I am new to javascript.

Can anyone help me to implement an onclick event on click of a HTML table row created through javascript?

Kindly note that I am inserting the data in table cells using innerHTML. Below is the code snippet of what i have tried.?

Java Script function:

function addRow(msg)
{
    var table = document.getElementById("NotesFinancialSummary");
    var finSumArr1 = msg.split("^");
    var length = finSumArr1.length-1;
    alert("length"+ length);
    for(var i=1; i<finSumArr1.length; i++)
    {
        var row = table.insertRow(-1);
        var rowValues1 = finSumArr1[i].split("|");
        for(var k=0;k<=10;k++)
        {       
            var cell1 = row.insertCell(k);
            var element1 = rowValues1[k];
            cell1.innerHTML = element1;     
        }   


    }

        for(var i=1; i<rowCount; i++)
        {
            for(var k=0;k<=10;k++)
            {   
                document.getElementById("NotesFinancialSummary").rows[i].cells[k].addEventListener("click", function(){enableProfileDiv()}, false);


            }
        }       

}

HTML table code in jsp :

     <TABLE id="NotesFinancialSummary" width="800px" border="1" align="left" >
<tr >

                <th>Symbol</th>
                <th>Claimant</th>
                <th>MJC</th>
                <th>S</th>
                <th>Type</th>
                <th>Indemnity Resv</th>
                <th>Indemnity Paid</th>
                <th>Medical Resv</th>
                <th>Medical Paid</th>
                <th>Legal Resv</th>
                <th>Legal Paid</th>
     </tr>
      <tr>
                    <td>
                    </td>
                    <TD> </TD>          
                    <TD> </TD>
                    <TD> </TD>          
                    <TD> </TD>
                    <TD> </TD>          
                        <TD> </TD>
                        <TD> </TD>  
                        <TD> </TD>  
                        <TD> </TD>  
                        <TD> </TD>  
        </tr>



    </table>

I am new to javascript.

Can anyone help me to implement an onclick event on click of a HTML table row created through javascript?

Kindly note that I am inserting the data in table cells using innerHTML. Below is the code snippet of what i have tried.?

Java Script function:

function addRow(msg)
{
    var table = document.getElementById("NotesFinancialSummary");
    var finSumArr1 = msg.split("^");
    var length = finSumArr1.length-1;
    alert("length"+ length);
    for(var i=1; i<finSumArr1.length; i++)
    {
        var row = table.insertRow(-1);
        var rowValues1 = finSumArr1[i].split("|");
        for(var k=0;k<=10;k++)
        {       
            var cell1 = row.insertCell(k);
            var element1 = rowValues1[k];
            cell1.innerHTML = element1;     
        }   


    }

        for(var i=1; i<rowCount; i++)
        {
            for(var k=0;k<=10;k++)
            {   
                document.getElementById("NotesFinancialSummary").rows[i].cells[k].addEventListener("click", function(){enableProfileDiv()}, false);


            }
        }       

}

HTML table code in jsp :

     <TABLE id="NotesFinancialSummary" width="800px" border="1" align="left" >
<tr >

                <th>Symbol</th>
                <th>Claimant</th>
                <th>MJC</th>
                <th>S</th>
                <th>Type</th>
                <th>Indemnity Resv</th>
                <th>Indemnity Paid</th>
                <th>Medical Resv</th>
                <th>Medical Paid</th>
                <th>Legal Resv</th>
                <th>Legal Paid</th>
     </tr>
      <tr>
                    <td>
                    </td>
                    <TD> </TD>          
                    <TD> </TD>
                    <TD> </TD>          
                    <TD> </TD>
                    <TD> </TD>          
                        <TD> </TD>
                        <TD> </TD>  
                        <TD> </TD>  
                        <TD> </TD>  
                        <TD> </TD>  
        </tr>



    </table>
Share Improve this question edited Jul 12, 2013 at 9:41 user2573586 asked Jul 11, 2013 at 23:54 user2573586user2573586 711 gold badge2 silver badges13 bronze badges 3
  • 1 You should post some code showing us how you're inserting the table row – nicosantangelo Commented Jul 11, 2013 at 23:57
  • Do you mean for a specific row in the table or all of them? – agelber Commented Jul 11, 2013 at 23:58
  • @NicoSantangelo please refer to the code snippet attached – user2573586 Commented Jul 12, 2013 at 9:44
Add a ment  | 

5 Answers 5

Reset to default 2

<table id="table"></table>

$("#table").append("<tr><td>Hi there</td></tr>");

$("#table").on( "click", "tr", function(){
    // do something
    alert( $(this).children("td:first").text() );
});

Any time the click event bubbles up to <table id="table">, this function will be called (no matter if the <tr>s are inserted dynamically, or hard coded).

This will require the jQuery library

  • http://jquery./
  • http://api.jquery./on/

One way to do it would be using document.createElement

Instead of doing:

yourParentElement.innerHTML = "<tr>Something</tr>";

You can do

var tr = document.createElement("tr");
tr.innerHTML = "Something";
tr.onclick = function() {
    //code to be executed onclick
};
yourParentElement.appendChild(tr);

Another way, would be to use an id (only if you're doing this once, you don't want duplicated ids):

yourParentElement.innerHTML = "<tr id='someId'>Something</tr>";
document.getElementById("someId").onclick = function() { //fetch the element and set the event

}

You can read more about events here, but just so you have an idea onclick will only let you set one function. If you want a better solution you can use something like addEventListener, but it's not crossbrowser so you may want to read up on it.

Lastly, if you want to set up an event on every tr you can use:

var trs = document.getElementByTagName("tr"); //this returns an array of trs
//loop through the tr array and set the event

after you insert your <tr> using innerHTML, create a click event listener for it.

document.getElementById("the new id of your tr").addEventListener("click", function() {
     what you want to do on click;
});

Something like this: http://jsfiddle/gnBtr/

var startEl = document.getElementById('start');
var containerEl = document.getElementById('container');

var inner = '<div id="content" style = "background: pink; padding:20px;" > click on me </div>'

// Function to change the content of containerEl
function modifyContents() {
  containerEl.innerHTML = inner;
  var contentEl = document.getElementById('content');
  contentEl.addEventListener("click", handleClickOnContents, false);
}

// listenting to clikc on element created via innerHTML
function handleClickOnContents() {
  alert("you clicked on a div that was dynamically created");
}

// add event listeners
startEl.addEventListener("click", modifyContents, false);

Check it out:

$('#your_table_id tbody').on('click', 'tr', function (e) {
    $('td', this).css('background-color', 'yellow');
} );

css:

tr:hover td{
    background-color: lightsteelblue !important;
}

It works fine for me, specially when I'm using jquery dataTable pagination.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论