如何将eventListener添加到第一列的每个单元格?

时间:2019-06-20 08:41:03

标签: javascript html-table addeventlistener innertext

此代码仅适用于第一列的第一个单元格。当我单击单元格时,警报显示单元格的innerText。我希望在第一列的每个单元格上启动警报,并显示单击的单元格的文本。怎么做?我是javascript新手,很抱歉,谢谢您的宝贵时间。

const http = require('http');
const mysql = require('mysql');

const pool = mysql.createPool({
  host: '127.0.0.1',
  user: 'andrea',
  password: '*********',
  database: 'andrea',
  charset: 'utf8'
});

//html string that will be send to browser
var reo ='<html><head><title>Table From SQL</title></head><body><h1>Table From SQL</h1>{${table}}</body></html>';

//sets and returns html table with results from sql select
//Receives sql query and callback function to return the table
function setResHtml(sql, cb){
  pool.getConnection((err, con)=>{
    if(err) throw err;

    con.query(sql, (err, res, cols)=>{
      if(err) throw err;

      var table =''; //to store html table

      //create html table with data from res.
      for(var i=0; i<res.length; i++){
        table +='<tr><td id="peso" style="cursor:pointer">'+ res[i].peso +'</td><td>'+ res[i].vita +'</td><td>'+ res[i].data +'</td></tr>';
      }
      table ='<table border="1" id="table1"><tr><th>Peso</th><th>Vita</th><th>Data</th></tr>'+ 
      table +'</table>';
      table = table += '<script>var peso = window.document.getElementById("peso");'+
        'peso.addEventListener("click", functionOnClick, false);'+
        'function functionOnClick(){alert(peso.innerText);}</script>'

      con.release(); //Done with mysql connection

      //const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);


      return cb(table);
    });
  });
}



let sql ='SELECT * FROM registropeso';

//create the server for browser access
const server = http.createServer((req, res)=>{
  setResHtml(sql, resql=>{
    reo = reo.replace('{${table}}', resql);
    res.writeHead(200, {'Content-Type':'text/html; charset=utf-8'});
    res.write(reo, 'utf-8');
    res.end();
  });
}).listen(8080);

/*
server.listen(8080, ()=>{
  console.log('Server running at //localhost:8080/');
});
*/

2 个答案:

答案 0 :(得分:1)

您可以选择作为行中第一个td的每个元素。然后,您可以循环浏览这些事件并添加事件侦听器。 document.querySelectorAll("#table1 td:first-child");将选择这些元素。在事件监听器中,您可以使用this来获取已单击的元素。

const http = require('http');
const mysql = require('mysql');

const pool = mysql.createPool({
    host: '127.0.0.1',
    user: 'andrea',
    password: '*********',
    database: 'andrea',
    charset: 'utf8'
});

//html string that will be send to browser
var reo = '<html><head><title>Table From SQL</title></head><body><h1>Table From SQL</h1>{${table}}</body></html>';

//sets and returns html table with results from sql select
//Receives sql query and callback function to return the table
function setResHtml(sql, cb) {
    pool.getConnection((err, con) => {
        if (err) throw err;

        con.query(sql, (err, res, cols) => {
            if (err) throw err;

            var rows = ''; //to store html rows

            //create html table with data from res.
            for (var i = 0; i < res.length; i++) {
                rows += `<tr><td style="cursor:pointer">${res[i].peso}</td><td>${res[i].vita}</td><td>${res[i].data}</td></tr>`;
            }

            var table = `<table border="1" id="table1"><tr><th>Peso</th><th>Vita</th><th>Data</th></tr>${rows}</table>`;

            table += `
                <script>
                function functionOnClick() {
                    alert(this.innerText);
                }

                var pesoElements = document.querySelectorAll("#table1 td:first-child");
                pesoElements.forEach(function(peso) {
                    peso.addEventListener("click", functionOnClick, false);
                })
                </script>`;

            con.release(); //Done with mysql connection

            //const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);


            return cb(table);
        });
    });
}

注意:我已经使用Template literals来清除代码中的内容。

答案 1 :(得分:0)

如下更新部分代码:

for(var i=0; i<res.length; i++){
        table +='<tr><td id="peso" style="cursor:pointer">'+ res[i].peso +'</td><td>'+ res[i].vita +'</td><td>'+ res[i].data +'</td></tr>';
      }
      table ='<table border="1" id="table1"><tr><th>Peso</th><th>Vita</th><th>Data</th></tr>'+ 
      table +'</table>';
      table = table += '<script>var peso = window.document.getElementById("peso");'+
        'peso.addEventListener("click", functionOnClick, false);'+
        'function functionOnClick(){alert(peso.innerText);}</script>'

for(var i=0; i<res.length; i++){
        table +='<tr><td id="peso'+i+'" style="cursor:pointer">'+ res[i].peso +'</td><td>'+ res[i].vita +'</td><td>'+ res[i].data +'</td></tr>';
        table += '<script>var peso = window.document.getElementById("peso'+i+'");'+
        'peso.addEventListener("click", functionOnClick, false);'+
        'function functionOnClick(){alert(peso.innerText);}</script>'
      }
      table ='<table border="1" id="table1"><tr><th>Peso</th><th>Vita</th><th>Data</th></tr>'+ 
      table +'</table>';

说明:

您正在通过循环将相同的ID分配给多个TD。

串联 i 将使每个TD的ID唯一。