简体   繁体   中英

JavaScript add Onclick Event

How can i add a onclick event to a certain td cell of a table ?

I have a form in which i have a field where i want to display something on click:

<input type="text" name="tip">

This is the function i am using :

function setText(day, hour){
    var tipField = document.getElementsByName('tip');
    tipField.value = day + "  " + hour;
}

And here i am trying to add onClick event to td's(those ids are td's ids):

el[0] = document.getElementById('j1');
el[1] = document.getElementById('j2');
el[2] = document.getElementById('j3');
el[3] = document.getElementById('j4');
el[4] = document.getElementById('j5');

First method:

el[1].onclick="setText('Monday', '10:00')";

Second method:

el.addEventListener("click", function(){
                setText('Joi','09:00');
            });

But none seems to work.

You can use AddEventListener("EVENT",FUNCTION_NAME) for dynamically add listener. Here we add CLICK for all <tr> of table

 var table = document.getElementById("our_table"); console.log(table); function DOIT(){ console.log("TR Clicked"); } for(i=0;i<=table.childElementCount;i++){ table.rows[i].addEventListener("click",DOIT); } 
 <table id="our_table"> <tr><td>Name</td><td>Family</td> </tr> <tr><td>First Name</td><td>Last Name</td> </tr> </table> 

open console for see result.

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