如何将Javascript事件绑定到动态类

时间:2015-04-22 17:17:37

标签: javascript jquery javascript-events

当该类的任何成员具有鼠标悬停时,我需要为同一类的所有成员生成背景颜色更改。

这是JavaScript:

var array = ['abc','def','abc','xyz'];
var row;
var cell = [];
var rowClass = [];

for (var i = 0; i < array.length; i++){
    // Insert an empty <tr> element
    row = document.getElementById("myTable").insertRow(i+1);

    // Insert cells <td></td>
    for(var j = 0; j < 2; j++){
        cell[j] = row.insertCell(j);
    };

    // fill cells <td></td>
    cell[0].innerHTML = 'row ' + i;
    cell[1].innerHTML = array[i];
    cell[1].setAttribute("class", array[i]);
}
var k0 = 0;
rowClass[k0] = '.' + array[k0];
$(document).on('mouseover', rowClass[k0] ,function() {$(rowClass[k0]).css("background-color", "yellow");});
$(document).on('mouseout', rowClass[k0] ,function() {$(rowClass[k0]).css("background-color", "");});

var k1 = 1;
rowClass[k1] = '.' + array[k1]; 
$(document).on('mouseover', rowClass[k1] ,function() {$(rowClass[k1]).css("background-color", "yellow");});
$(document).on('mouseout', rowClass[k1] ,function() {$(rowClass[k1]).css("background-color", "");});

var k2 = 2;
rowClass[k2] = '.' + array[k2];
$(document).on('mouseover', rowClass[k2] ,function() {$(rowClass[k2]).css("background-color", "yellow");});
$(document).on('mouseout', rowClass[k2] ,function() {$(rowClass[k2]).css("background-color", "");});

var k3 = 3;
rowClass[k3] = '.' + array[k3];
$(document).on('mouseover', rowClass[k3] ,function() {$(rowClass[k3]).css("background-color", "yellow");});
$(document).on('mouseout', rowClass[k3] ,function() {$(rowClass[k3]).css("background-color", "");});

这是JSfiddle

如何使用正确的代码替换四个明确的'on'语句hack?在Stack Overflow上尝试循环和各种答案之后,这是我能做的最好的工作。

1 个答案:

答案 0 :(得分:1)

  

如何更换四个明确的&#39; on&#39;声明破解正确的代码?尝试循环后......

您可以使用悬停事件代替mouseover&amp; mouseout。它可能在循环中不适合你的原因是因为你试图在事件回调中使用索引i。这是展示问题的fiddle

我认为这是一种可以说是更清晰的编写代码的方法。解释内容包括评论。

&#13;
&#13;
jQuery(function($) {
  var table = $('#myTable'),
      classes = ['abc', 'def', 'abc', 'xyz'];

  $.each(classes, function(index, class_name) {

    // create a table row and append 2 table cells to it
    var tr = $('<tr>').append([
      $('<td>', {
        'text': 'row ' + index
      }),
      $('<td>', {
        'text': class_name,
        'class': class_name
      }).hover(
        // replaces mouseover
        hoverEffect('yellow', class_name),
        // replaces mouseout
        hoverEffect('inherit', class_name)
      )
    ]);

    table.append(tr);
  });

  function hoverEffect(color, class_name) {
    // a function must be returned for the hover effect to work
    return function() {
      // this function closes over color and class_name
      $('.' + class_name).css('background-color', color);
    };
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<table id="myTable" width="100" cellpadding="3" border="1">
  <tr>
    <td>column1</td>
    <td>column2</td>
  </tr>
</table>
&#13;
&#13;
&#13;