Javascript函数参数引用html元素

时间:2015-04-28 10:50:29

标签: javascript html function

出于有趣的目的,我想用javascript创建一个100x100的html表,并使用onmouseover来改变颜色。它就像一种简单的绘画方式,但是当我将onmouseover更改为changeColor函数时,参数是ClientXClientY位置而不是html元素。

function createTabel(){
    var div = document.getElementById("paint");
    var table = document.createElement("table");
    table.style.border = "1px solid black";
    for (var i = 0; i < 100; i++){
        var row = document.createElement("tr");
        for (var j = 0; j <100; j++){
            var cell = document.createElement("td");

            cell.onmouseover = changeColor;

            cell.style.height = "3px";
            cell.style.width = "3px";
            cell.style.padding = "0";
            cell.style.margin = "0";

            row.appendChild(cell);
        }
        table.appendChild(row);
    }
    div.appendChild(table);
}

和changeColor函数:

function changeColor(cell){
    var color = document.getElementById("color").value;
    cell.style.backgroundColor = color;
}

如何在没有id的情况下访问导致事件的html元素?

2 个答案:

答案 0 :(得分:2)

尝试事件:

function changeColor(e){
    e = e || window.event;
    var el = e.srcElement || e.target; //get the current element(cell)
    var color = document.getElementById("color").value;
    el.style.backgroundColor = color;
}

答案 1 :(得分:-1)

请以更强大的方式附加活动,以便活动适用于所有浏览器。

for (var j = 0; j < 100; j++){
    var cell = document.createElement("td");
    addEvent(cell, 'mouseover', changeColor); // See method in code below.
    // ...
}

// Attach the event to all table cells.
[].slice.call(document.querySelectorAll('td')).forEach(function(td) {
  addEvent(td, 'mouseover', changeColor);
});

function changeColor(e) {
    e = e || window.event; // Is the event local or global?
    var el = e.srcElement || e.target; // The element who dispatched the event.
    el.style.backgroundColor = 'red';
}

// Cross-browser event listener.
function addEvent(el, event, fn, useCapture) {
  if (el.addEventListener) {
    el.addEventListener(event, fn, useCapture);
  } else {
    el.attachEvent('on' + event, function() {
      // Call the event with the scope of the target element.
      return fn.call(el, window.event);   
    });
  }
}
<table>
  <thead><tr><th>th1</th><th>th2</th></tr></thead>
  <tbody><tr><td>td1</td><td>td2</td></tr><tbody>
</table>

如上所述,您可以使用一点点jQuery来实现相同的效果。 jQuery的事件侦听器为您设置目标元素的范围。这使事件处理更容易。

$(function() {
  $('table').on('mouseover', 'td', changeColor);

  function changeColor(e) {
    $(this).css('background-color', 'red');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <thead><tr><th>th1</th><th>th2</th></tr></thead>
  <tbody><tr><td>td1</td><td>td2</td></tr><tbody>
</table>