HTML “onclick” event in JavaScript (In a table)

▼魔方 西西 提交于 2019-12-06 13:43:18

Your style of Javascript programming is ancient, to say the least. document.write is a function developed mainly when there were almost no common methods to generate dynamic content.

So, you should generate your elements dynamically with methods like document.createElement, append your content there, then attach the elements to the DOM with modern methods like appendChild.

Then, you can attach event listeners using something more modern than the traditional way like onclick, like addEventListener. Here's a snippet:

var td = document.createElement("td");
td.innerHTML = getDate(1, "plan", "r1c1");
td.addEventListener("click", function() {
    getTicket(1, 'plan', 1);
});
row.appendChild(td);

I supposed that row is the row of the table that you're generating.

Unfortunately, IE<9 uses a different method called attachEvent, so it'd become:

td.attachEvent("onclick", function() { ...

You can modify attributes in HTML using function setAttribute(Attribute, Value).

With this function you can generate the cell code and define dinamically the attribute.

You should not use document.write to add elements to your page, there are javascript functions for this:

var myCell = document.createElement('td');
myCell.setAttribute('id', 'r1c1');
myCell.setAttribute('align', 'center');
myCell.onclick = function () {
    getTicket(1, 'plan', 1);
};

// myRow is the 'tr' you want this 'td' to be a child of.
myRow.appendChild(myCell);

See it in action: http://jsfiddle.net/teH7X/1/

Can you please try below code, if that is working then let me know I will give you some better option:-

<script>
   document.onload = function()
   {
       document.getElementById('r1c1').onclick = function()
       {
           getTicket(1,'plan',1);
       }
   }
</script>

Please check and let me know.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!