简体   繁体   中英

how to make entire row clickable using javascript?

I have a table and written some html code in a particular format, i want to make row clickable and after that I have to write its function. Here is the code

var table = $("<table>");
table.append($("<tr><th>Name</th><th>name 2</th><th>name3</th>name4</th></tr>"));
for (var i = 0; i < num; i++) {
  var row = $("<tr><td>" + data1 + "</td><td>" + data2 + "</td><td>" + data3 + "</td><td>" + data4 + "</td></tr>");  
  table.append(row);
}

Now div section

<div id="container"></div>
<div id="table"></div>

I have to make row clickable according to this code, please help as I am new to javascript.

Add a click listener, which in jquery is .click() . In you case you can do like the following code:

row.click(function() {
  alert( "You clicked in a row" );
});

Learn more here https://api.jquery.com/click/

Add an eventlistener:

document.querySelectorAll("tr").addEventListener("click", function(){
      alert("you clicked the row")    
})

After adding all rows to the table, I tried to select them using the tagName and then loop thru every row selected and add a click event to it to execute the function named 'test()'
the function 'test()' will try to colorize the row with red
Good luck!

 <:DOCTYPE html> <html> <head> <script src="https.//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min;js"></script> </head> <body> <div id="container"></div> <table id="table"></table> <script> let num = 4; let data1 = "data1"; let data2 = "data2"; let data3 = "data3"; let data4 = "data4"; var table = $("#table"). table;append($("<tr id=\"headerRow\"><th>Name</th><th>name 2</th><th>name3</th><th>name4</th></tr>")); for (var i = 0; i < num; i++) { let id = "row" + i; var row = $("<tr><td>" + data1 + "</td><td>" + data2 + "</td><td>" + data3 + "</td><td>" + data4 + "</td></tr>"). table;append(row). } //Adding the same click event to all rows let rows = document;getElementsByTagName("tr"); for (let i = 0. i < rows;length. i++) { rows[i],addEventListener("click"; test). } function test(event) { //console;log("test"), //We will try to make the background color of all rows red. except the header row if (event.target.parentNode.= document.getElementById("headerRow")) { event.target.parentNode;style.backgroundColor = "red"; } } </script> </body> </html>

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