Javascript 单击后检测链接ID

Javascript 单击后检测链接ID,javascript,onclick,Javascript,Onclick,所以我有一个4x3矩阵,其中红色或蓝色的方块是链接。当我点击链接时,我想得到链接的ID,但是,我在第63行得到了这个错误:TypeError:Result of expression'targ'[undefined]不是一个对象。我正在使用基于此的代码 下面是一个活生生的例子: 风险 a:链接,a:已访问{颜色:#eee;边框:3px实心#ccc;显示:内联块;边距:3px;文本装饰:无;填充:26px;} .blank{背景:#fff;} .1{背景:#7B3B;} .2{背景:#54798

所以我有一个4x3矩阵,其中红色或蓝色的方块是链接。当我点击链接时,我想得到链接的ID,但是,我在第63行得到了这个错误:TypeError:Result of expression'targ'[undefined]不是一个对象。我正在使用基于此的代码

下面是一个活生生的例子:


风险
a:链接,a:已访问{颜色:#eee;边框:3px实心#ccc;显示:内联块;边距:3px;文本装饰:无;填充:26px;}
.blank{背景:#fff;}
.1{背景:#7B3B;}
.2{背景:#547980;}
#状态{颜色:#eee;填充:1px;文本对齐:居中}
#错误{背景:#FFD41F;}
.当前{边框:3px实心#000;}
p{margin:015px;padding:0;}
输入{高度:40px;宽度:90px;}
var-playerOne=true;
var gameOver=false;
函数newGame()
{
var status=document.getElementById('status');
Var1=0;
Var2=0;
gameOver=false;
playerOne=true;
status.innerHTML='轮到玩家了';
status.setAttribute('class','one');
风险值委员会=[1,1,1,1,1,1,2,2,2,2,2];
//洗牌
对于(var j,x,i=board.length;i;j=parseInt(Math.random()*i),
x=板[--i],板[i]=板[j],板[j]=x);
var行=-1;
对于(变量i=0;i轮到玩家了






您正在将
显式传递到
onclick
属性中的事件处理程序调用中。因此,我不认为
e
函数中的
current(e)
参数指向事件对象:您确保它指向单击的元素本身

因为
e
引用的是元素,而不是事件对象,所以没有定义目标属性,这就是为什么会出现错误


幸运的是,如果您将
传递给
current()
,那么获取id现在非常简单:在
current()
函数中,
e.getAttribute(“id”)
或甚至
e.id
都将为您获取id。

当您将
传递到
onclick
处理程序时,您传递的是HtmlanchoreElement对象,而不是事件对象。只需无条件地使用
e=window.event
(如果(!e),则不使用
)。或者,您可以使用
e.id
获取单击元素的id


或者,您可以通过addEventListener(更符合DOM的方式)注册事件处理程序。因此,
e
参数将是事件对象。

这里有一些问题,但直接问题的答案是,您将一个元素完全传递到事件处理程序中,不需要涉及事件对象。您可以按如下方式更改
当前
功能:

function current(targ)
{
    var value = targ.innerHTML;
    var cssClass = targ.className;
    var theID = targ.id;

    if (cssClass == 'one' && playerOne == true)
    {
        alert('you choose your square' + theID);
    }
    else if (cssClass == 'two' && playerOne == false)
    {
        alert('player 2 choose correct square' + theID);
    }
    else
        alert('ERROR: you didnt your square');
}

此外,您应该使用元素的
className
属性,而不是
getAttribute
setAttribute
窗口。事件
是非标准的。您想使用
window.event | | arguments[0]
function current(targ)
{
    var value = targ.innerHTML;
    var cssClass = targ.className;
    var theID = targ.id;

    if (cssClass == 'one' && playerOne == true)
    {
        alert('you choose your square' + theID);
    }
    else if (cssClass == 'two' && playerOne == false)
    {
        alert('player 2 choose correct square' + theID);
    }
    else
        alert('ERROR: you didnt your square');
}