js代码:indow.onload=function a()
{var nodes=document.getElementsByTagName('a');
nodes[3].onclick='alert(this.title)';}
html代码:
<a href='#' onclick='a();' title='china'>中国</a>
就弹不出标题,但是换成
nodes[3].onclick=function()
{
alert(this.title);
}
就可以弹出标题窗口了,为什么?难道js里的onclick只能跟function的匿名函数吗?感到困惑,请js高手指点一下。javascript 弹窗
{var nodes=document.getElementsByTagName('a');
nodes[3].onclick='alert(this.title)';}
html代码:
<a href='#' onclick='a();' title='china'>中国</a>
就弹不出标题,但是换成
nodes[3].onclick=function()
{
alert(this.title);
}
就可以弹出标题窗口了,为什么?难道js里的onclick只能跟function的匿名函数吗?感到困惑,请js高手指点一下。javascript 弹窗
<a href='#' onclick='a();' title='china'>中国</a> 这样写 a() 里 this 不是A 而是window
但是去掉单引号,确弹窗undefined,而不会弹出正确的标题,为什么呢?
你可以写成
<a href='#' onclick='a.call(this);' title='china'>中国</a>
或 传参进去
<a href='#' onclick='a(this);' title='china'>中国</a>
但是去掉单引号,确弹窗undefined,而不会弹出正确的标题,为什么呢?
去掉单引号是把aler()这个执行的函数返回值赋值给nodes[3].onclick属性,而alert(this.title)没返回值,只执行,其中this是window,window没title属性,即undefined