js修改onclick动作的四种方法(推荐)

第一种:button.onclick = Function("alert('hello');");

第二种:button.onclick = function(){alert("hello"); };

第三种:button.onclick = myAlert;

              function myAlert(){
                     alert("hello");
              }

第四种:

这种情况更加动态,更为实用,而且还能添加多个函数(添加的事件的顺序即执行顺序),呵呵

?
1
2
3
4
5
6
7
8
if (window.addEventListener){ // Mozilla, Netscape, Firefox
     //element.addEventListener(type,listener,useCapture);
     button.addEventListener( 'click' , alert( '11' ), false );
     button.addEventListener( 'click' , alert( '12' ), false ); //执行顺序11 -> 12
   } else { // IE
     button.attachEvent( 'onclick' , function (){alert( '21' );});
     button.attachEvent( 'onclick' , function (){alert( '22' );});执行顺序22 -> 21
   }

实例讲解:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
button.onclick = Function ( "alert('31');" );
   button.onclick = Function ( "alert('32');" );
   button.onclick = Function ( "alert('33');" ); //如果这样写,那么将会只有最后一个方法被执行
 
   button.attachEvent( "onclick" , function (){alert( '41' );});
   button.attachEvent( "onclick" , function (){alert( '42' );});
   button.attachEvent( "onclick" , function (){alert( '43' );}); //如果这样写,三个方法都会被执行
 
   // 当然,你也可以这样写
   button.onclick = Function( "alert('51');" );
   button.attachEvent( "onclick" , function (){alert( '52' );});
 
    //对应移除事件
   detachEvent( 'onclick' ,func); //ie下使用删除事件func
   removeEventListener( 'click' ,func); //Mozilla下,删除事件func

猜你喜欢

转载自blog.csdn.net/weixin_39214481/article/details/81035594