Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
引用html元素的Javascript函数参数_Javascript_Html_Function - Fatal编程技术网

引用html元素的Javascript函数参数

引用html元素的Javascript函数参数,javascript,html,function,Javascript,Html,Function,出于好玩的目的,我想用javascript创建一个100x100 html表,并使用onmouseover更改颜色。这就像一种简单的绘画方式,但是,当我将onmouseover更改为changeColor函数时,参数是ClientX和ClientY位置,而不是html元素 function createTabel(){ var div = document.getElementById("paint"); var table = document.createElement("t

出于好玩的目的,我想用javascript创建一个100x100 html表,并使用
onmouseover
更改颜色。这就像一种简单的绘画方式,但是,当我将
onmouseover
更改为
changeColor
函数时,参数是
ClientX
ClientY
位置,而不是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);
}
如何在没有id的情况下访问导致事件的html元素?

请改为尝试事件:

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;
}

请以更健壮的方式附加事件,以便事件在所有浏览器中都能工作

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

th1th2
td1td2

event.target
将为您提供导致事件的dom元素。当他只需要
e.srceelement | | e.target
时,添加所有这些复杂性有何帮助?这是附加事件的正确方法,与海报所做的没有太大区别。此外,它还处理为小于9的IE版本添加事件。
for (var j = 0; j < 100; j++){
    var cell = document.createElement("td");
    addEvent(cell, 'mouseover', changeColor); // See method in code below.
    // ...
}