使用JS创建单元格表并尝试单独访问它们

时间:2018-08-27 16:49:40

标签: javascript html

因此,我有一个空表,当按下按钮时,表中会填充内容。每个表格行中仅包含一个单元格,该单元格的内容为字符串。这些字符串预先包含在数组中。因此,当用户按下按钮时,就会发生这种情况:

function buttonClicked()
{
    for(i = 0; i < list.length; i++) 
    {
        table = document.getElementById("my_table");
        row = table.insertRow(0);
        cell = row.insertCell(0);
        cell.innerHTML = list[i];
    }
}

该表正在按计划创建,但是当我在程序运行时尝试通过鼠标分别访问这些单元格时出现问题。目的是能够单击内容,然后程序应显示表的单击内容唯一的特定图像。我不知道如何单独访问这些单元格,因为JS在程序启动时会创建它们。因此,除了空表标记外,HTML代码中没有其他要处理的内容。请让我知道这是否是做这种事情的正确方法。我知道这可能是一个非常简单的问题,但是我是新手程序员,甚至不知道如何针对此问题在google / stackoverflow上进行搜索,因为它很难解释。

3 个答案:

答案 0 :(得分:0)

为元素创建分配点击处理程序:

const list = [
  "//placehold.it/60x60/0bf",
  "//placehold.it/60x60/f0b",
];

const populate_my_table = () => list.forEach((item, i) => {

    const row = my_table.insertRow(-1), // Append to table using -1
      cell = row.insertCell(0),
      img = document.createElement("img"); // "img" or the selector you need

    img.src = item;
    img.addEventListener("click", evt => {
      console.log( evt.target.src ); // Do something on click
    });
    cell.textContent = `IMAGE:${i+1}`;
    cell.appendChild(img);
});

document.getElementById("my_button").addEventListener("click", populate_my_table);
<button id="my_button">LOAD IMAGES</button>
<table id="my_table"></table>

答案 1 :(得分:0)

您可以通过两种方式访问​​单元格,具体取决于“访问”的含义。

首先,您可以使用DOM Table API并指定要使用的行索引和单元格索引,然后可以随时与表中的行和/或单元格进行交互并“访问”:

// Button to make table
document.querySelector("button").addEventListener("click", buttonClicked);

// Table data items
let list = ["Red", "White", "Blue", "Yellow", "Green"];

// Declare the variable outside of the loop so that you don't have to
// re-scan for it over and over.
let table = document.getElementById("my_table"); 

function buttonClicked()
{
    for(i = 0; i < list.length; i++) 
    {
        let row = table.insertRow(0);
        let cell = row.insertCell(0);

        // Use .textContent when the content isn't HTML as it's quicker and safer
        cell.textContent = list[i]; 
    }
      
    
   // Let's get our hands on the "Blue" cell
   let blue = table.rows[2].cells[0]; 

   // Now, do whatever you want with it
   blue.style.fontWeight = "bold";
   blue.classList.add("Blue");
}
table, td { border:1px solid black; margin:1em; }
.Red { background-color: #f00; }
.White { background-color: #fff; }
.Blue { background-color: #33f; color:#fff; }
.Yellow { background-color: #ff0; }
.Green { background-color: #0f0; }
<button type="button">Make Table</button>
<table id="my_table"></table>

第二,您可以在创建单元格时在它们上设置事件回调,以便可以对用户交互做出反应:

document.querySelector("button").addEventListener("click", buttonClicked);

let list = ["Red", "White", "Blue", "Yellow", "Green"];
let table = document.getElementById("my_table"); // Declare the variable outside of the loop

function buttonClicked()
{
    for(i = 0; i < list.length; i++) 
    {
        let row = table.insertRow(0);
        let cell = row.insertCell(0);
        cell.textContent = list[i]; // Use .textContent when the content isn't HTML
        cell.addEventListener("click", function(){
          // In this context, "this" refers to the element that triggered
          // the event we are handling -- the cell you clicked.
          alert("You clicked the: " + this.textContent + " cell.");
          this.classList.add(this.textContent);
        });
    }
}
table, td { border:1px solid black; margin:1em; }
.Red { background-color: #f00; }
.White { background-color: #fff; }
.Blue { background-color: #33f; color:#fff; }
.Yellow { background-color: #ff0; }
.Green { background-color: #0f0; }
<button type="button">Make Table</button>
<table id="my_table"></table>

但是,最后一个示例设置了许多事件侦听器,这可能会影响性能。相反,我们可以在table上设置一个侦听器,并且由于events "bubble",单击单元格将弹出到可以拦截事件的表。然后,我们可以使用event.target找出事件的起源并采取相应的措施。之所以称为"Event Delegation",是更好的方法,不仅因为需要注册的事件处理程序更少,而且还因为以后创建的任何新单元格已经准备好参与事件过程。

document.querySelector("button").addEventListener("click", buttonClicked);

let list = ["Red", "White", "Blue", "Yellow", "Green"];
let table = document.getElementById("my_table"); // Declare the variable outside of the loop

// Set up the event at the table level instead of at each cell
table.addEventListener("click", function(event){
  alert("You clicked the: " + event.target.textContent + " cell.");
  event.target.classList.add(event.target.textContent);
});

function buttonClicked()
{
    for(i = 0; i < list.length; i++) 
    {
        let row = table.insertRow(0);
        let cell = row.insertCell(0);
        cell.textContent = list[i]; // Use .textContent when the content isn't HTML
    }
}
table, td { border:1px solid black; margin:1em; }
.Red { background-color: #f00; }
.White { background-color: #fff; }
.Blue { background-color: #33f; color:#fff; }
.Yellow { background-color: #ff0; }
.Green { background-color: #0f0; }
<button type="button">Make Table</button>
<table id="my_table"></table>

答案 2 :(得分:0)

尝试一下:

$('#my_table tr td').onClick(function(){
    console.log('click in cell');
});