JS 触发单击 事件

JS触发单击事件的两种方式onclick和click函数:

document.getElementById("test").onclick();

document.getElementById("test").click();

两者之间的区别:

  1. onclick()  方式类似于方法的调用,只执行onclick指定的函数,并不代表一次单击事件

  2. click() 方式相当于一次单击事件

    以下举例说明:
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    
    </head>
    <body>
    	<div onclick="test1();">
    		<a href="http://www.baidu.com" id="test" onclick="test();">hello</a>
    	</div>
    </body>
    </html>
    <script type="text/javascript">
    	document.getElementById("test").onclick();//1
    	//document.getElementById("test").click();//2
    	function test() {
    		alert(12);
    	}
    </script>
    执行1 时,页面弹出对话框,但页面不跳转。
    执行2 时,先弹出对话框,然后页面跳转。

猜你喜欢

转载自hello-world-hello.iteye.com/blog/2212297
今日推荐