简体   繁体   English

如何使用 javascript 使整行可点击?

[英]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.我有一个表格并以特定格式编写了一些 html 代码,我想让行可点击,然后我必须编写它的 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 部分

<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.我必须根据此代码使行可点击,请帮助,因为我是 javascript 的新手。

Add a click listener, which in jquery is .click() .添加一个点击监听器,在 jquery 中是 .click .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/在此处了解更多信息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()'将所有行添加到表中后,我尝试使用 tagName 对它们进行 select 然后循环选择每一行并向其添加点击事件以执行名为“test()”的 function
the function 'test()' will try to colorize the row with red function 'test()' 将尝试用红色为行着色
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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM