请看下面的程序: <button onclick="aa()" id=btn>test</button> <SCRIPT LANGUAGE=javascript> <!-- function aa(){ alert("this is a test!") }function rr(){ alert("这是一个测试例子!") }btn.click=rr; btn.click(); </script>运行后,显示:"这是一个测试例子!" 点击按钮,显示:"this is a test!" 为什么重新定义的方法没改过来呢?
我想是你的程序错了 这样写就ok btn.onclick=rr; btn.onclick();
var aa=function(){alert('test')} document.onclick=aa aa() 这个代码有问题,不是吗
aa() 是对函数的调用
var nMenu=new Array();
function mRegiste(item){
mMenu[mMenu.length]=item;
return mMenu.length-1
}
function printMenu(){
var str=""
str+="标签:"+this.capture;
str+="连接:"+this.urlhref;
alert(str);
}function mainMenu(capture,url){
this.id=mRegiste(this);
this.prnMenu=printMenu;
this.capture=capture;
this.hrefurl=url;
}现在:var myMenu=new mainMenu("zhjzh","#")
我们看:alert(mMenu.lemgth)发现已经有东西料;
而调用 prnMenu 必须执行:myMenu.prnMenu()
才可以显示信息,执行printMenu().
是不是在自定义函数中加上括号就自动运行了呢?为什么?
var mMenu=new Array();function mRegiste(item){
mMenu[mMenu.length]=item;
return mMenu.length-1
}
function printMenu(){
var str=""
str+="标签:"+this.capture;
str+="连接:"+this.hrefurl;
alert(str);
}function mainMenu(capture,url){
this.id=mRegiste(this);
this.prnMenu=printMenu;
this.capture=capture;
this.hrefurl=url;
}
//现在:
var myMenu=new mainMenu("zhjzh","#")
//我们看:
alert(mMenu.length)
//发现已经有东西料;
//而调用 prnMenu 必须执行:
myMenu.prnMenu()
//才可以显示信息,执行printMenu().
//是不是在自定义函数中加上括号就自动运行了呢?为什么?
function是个对象我知道,在对象中定义方法时是不带括号的,带括号有成了什么呢?为什么在条用它本身时他就自己运行了呢?
<button onclick="aa()" id=btn>test</button>
<SCRIPT LANGUAGE=javascript>
<!--
function aa(){
alert("this is a test!")
}function rr(){
alert("这是一个测试例子!")
}btn.click=rr;
btn.click();
</script>运行后,显示:"这是一个测试例子!"
点击按钮,显示:"this is a test!"
为什么重新定义的方法没改过来呢?
这样写就ok
btn.onclick=rr;
btn.onclick();
document.onclick=aa
aa()
这个代码有问题,不是吗
document.onclick=aa
就自动运行了!为什么会是这样的呢?netdust(ND) 说的对。我把click onclick 当成一个事件了。
我的理解就是:不带括号就是对这个函数的引用,带括号就是对这个函数的调用,但当我们重新定义一个对象的事件时,本应该是引用,为什么又带括号呢?如:<button onclick="aa()">test</button>;为什么不是<button onclick="aa" id='tbn'>test</button>;如果重新定义时:tbn.onclick=aa,为什么又不是tbn.onclick=aa()呢?
function是个对象我知道,在对象中定义方法时是不带括号的,带括号有成了什么呢?为什么在条用它本身时他就自己运行了呢?
---------------------------------------------------------------------------做一下下面的试验你大概就明白了(两种定义事件的方法等效):<button id=a>buttona</button>
<button onclick="alert()" id=b>buttonb</button>
<SCRIPT LANGUAGE="JavaScript">
<!--
a.onclick=new Function("alert()")
alert(a.onclick)
alert(b.onclick)
//-->
</SCRIPT>其实<button onclick="...">并不是直接去调用引号中的语句,而是用引号中的语句去new一个Function对象,在Function对象中再调用该语句,所以要加上括号。
function aa() {
alert("你好")
}
document.onclick=aa // 将指针document.onclick指向函数aa,当发生点击事件时调用函数aa
document.onclick=aa() // 执行一次函数aa() ,与单独的aa() 或document.onclick()一样
</script>另外
var aa=new function(){alert('test')}
在创建一个对象时自然要执行其中的代码,很正常