【问题标题】:Adding unique Event Listener for an each td in table为表中的每个 td 添加唯一的事件侦听器
【发布时间】:2020-10-11 06:30:18
【问题描述】:

代码的目的是让每个块在鼠标悬停时显示不同的文本。我想再添加 30 个块,但我似乎无法找到一种方法来做到这一点,而不必为每个块创建不同的事件侦听器。是否可以通过使用数组和 for 循环的 mouseover 和 mouseout 的单个事件侦听器来执行此操作?
这就是 Javascript 和 HTML 代码的样子 V

var org = ["Anna", "Bob", "Caroline"]
var change = ["One", "Two", "Three"]

var headone = document.querySelector("#a");
headone.addEventListener('mouseover', function() {
  headone.textContent = change[0];
})
headone.addEventListener("mouseout", function() {
  headone.textContent = org[0];
})


var headtwo = document.querySelector("#b");
headtwo.addEventListener('mouseover', function() {
  headtwo.textContent = change[1];
})
headtwo.addEventListener("mouseout", function() {
  headtwo.textContent = org[1];
})

var headthree = document.querySelector("#c");
headthree.addEventListener('mouseover', function() {
  headthree.textContent = change[2];
})
headthree.addEventListener("mouseout", function() {
  headthree.textContent = org[2];
})
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>repl.it</title>

  <style>
    table {
      width: 80%;
    }
    
    td {
      width: 20%;
      position: relative;
      box-shadow: 0 4px 8px 2px rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
      background-color: white;
    }
    
    td:after {
      content: '';
      display: block;
      margin-top: 100%;
    }
    
    td:hover {
      background-color: pink;
      box-shadow: 0px 4px 24px 5px rgba(129, 120, 255, 1);
    }
    
    body {
      background-color: lightblue;
    }
  </style>

</head>

<body>
  <table>
    <tr>
      <td id="a">Anna</td>
      <td id="b">Bob</td>
      <td id="c">Caroline</td>
    </tr>
  </table>
</body>
<script src="test.js"></script>

</html>

有什么方法可以让 Javascript 部分更高效地使用数组?而不必为我添加到表中的每个新块创建一个新的 EventListener。

【问题讨论】:

    标签: javascript html dom frontend addeventlistener


    【解决方案1】:

    您可以使用一种索引,其中每个元素的 id 将确定它的组织和更改值。看看下面的代码:

    var org = ["Anna", "Bob", "Caroline"],
        change = ["One", "Two", "Three"];
    
    var test = document.querySelectorAll('td');
    
    // Loop to set id's and add eventlisteners 
    for(let i = 0; i < test.length; i++){
        test[i].id = i;
        test[i].addEventListener('mouseover', () => {
            test[i].textContent = change[i];
        });
        test[i].addEventListener('mouseout', () => {
            test[i].textContent = org[i];
        });
    }
    

    此代码按我认为您希望的方式工作。

    然而,这个 sn-p 是基于它们在代码中的放置顺序。当你玩它时你会看到:)

    【讨论】:

    • 哇哦!非常感谢,过去 2 天我一直在苦苦挣扎,试图弄清楚如何做到这一点。
    【解决方案2】:

    您可以编写一个函数,添加两个事件侦听器。然后我会抓住表格行并迭代它的孩子。每次迭代都会运行该函数,该函数会添加事件侦听器。

    function addEventListeners(target, index) {
        target.addEventListener('mouseover', function() {
            target.textContent = change[index];
        });
        target.addEventListener("mouseout", function() {
            target.textContent = org[index];
        });
    }
    
    var trChilds = document.querySelector('tr').children;
    for (let index = 0; index < trChilds.length; index++) {
        const element = trChilds[index];
        addEventListeners(element, index);
    }
    
    
    

    【讨论】:

      【解决方案3】:

      您可以将class 添加到您的td 元素,然后使用document.querySelectorAll() 返回具有该类的所有元素的数组。

      然后您可以使用forEach() 方法一次将更改应用于所有这些。您只需确保您的 change 数组与您在页面上呈现的 td 元素具有相同数量的元素。

      var org = ["Anna", "Bob", "Caroline"]
      var change = ["One", "Two", "Three"]
      
      const refs = document.querySelectorAll(".box");
      
      refs.forEach((ref, i) => {
          ref.addEventListener("mouseover", () => {
              ref.textContent = change[i]
          })
      
          ref.addEventListener("mouseout", () => {
              ref.textContent = org[i];
          })
      })
      <!DOCTYPE html>
      <html>
      
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <title>repl.it</title>
      
        <style>
          table {
            width: 80%;
          }
          
          td {
            width: 20%;
            position: relative;
            box-shadow: 0 4px 8px 2px rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
            background-color: white;
          }
          
          td:after {
            content: '';
            display: block;
            margin-top: 100%;
          }
          
          td:hover {
            background-color: pink;
            box-shadow: 0px 4px 24px 5px rgba(129, 120, 255, 1);
          }
          
          body {
            background-color: lightblue;
          }
        </style>
      
      </head>
      
      <body>
        <table>
          <tr>
            <td id="a" class="box">Anna</td>
            <td id="b" class="box">Bob</td>
            <td id="c" class="box">Caroline</td>
          </tr>
        </table>
      </body>
      <script src="test.js"></script>
      
      </html>

      【讨论】:

        【解决方案4】:
        give all td class of tds and then write the following code.
        
        
        let tabs=document.querySelectorAll(".tds");
        let i=0;
        tabs.forEach(e=>{
            e.addEventListener('mouseover',function(){
                e.textContent=change[i];
            })
            e.addEventListener('mouseout',function(){
                e.textContent=org[i];
            })
            i++
        })
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多