2015-04-28 18 views
1

爲了達到目的,我想用javascript創建100x100 html表格,並使用onmouseover更改顏色。它就像一個簡單的繪畫方式,但是當我將onmouseover更改爲changeColor函數時,參數是ClientXClientY的位置,而不是html元素。引用html元素的Javascript函數參數

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元素?

+1

'event.target'會給你造成該事件的DOM元素。 –

回答

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

請在更穩健的方式連接的情況下,這樣的事件將工作在所有瀏覽器。

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>

+0

如何在'e.srcElement || e.target'是他需要的嗎? – rxgx

+0

這是附加事件的正確方式,與海報的做法沒有太大區別。另外,它處理IE版本小於9的事件。 –

相關問題