2013-10-20 100 views
-1

我正在玩一些新的JavaScript函數來嘗試自動點擊網頁上的按鈕。javascript按鈕不會自動觸發點擊事件

但是,按鈕的點擊事件不會自動觸發。我搜索了一些代碼,看起來是正確的。

我使用的IE瀏覽器10

<html> 
<head> 
<script type = "text/javascript"> 
function haha1() 
{ 
    alert('haha1'); 
} 
</script> 

<script> 
    document.getElementById('haha').click(); 
</script> 
</head> 
<body> 
    <input type = "button" id = "haha" onClick = "haha1()" value = "lol"/> 
</body> 
</html> 

回答

2

您需要在頁面加載後去做。基本上,您的腳本在haha被創建之前執行,因此它不會顯示您的警報。

<script type = "text/javascript"> 
function haha1() 
{ 
    alert('haha1'); 
} 

function fire_haha() { 
    document.getElementById('haha').click(); 
} 
</script> 
</head> 
<body onLoad="fire_haha()"> 
1

與jQuery

function fire_haha() { 
      $('#haha').trigger('click'); 
} 
2

你必須等待DOM觸發事件和dccording到unobstrusive的JavaScript完全加載之後試試這個。你不應該將javascript嵌入到html中。

<html> 
<head> 
<script type = "text/javascript"> 
function haha1() 
{ 
    alert('haha1'); 
} 
</script> 

<script> 
    window.onload = function(){ 
    document.getElementById('haha').onclick = function(){ 
     haha1(); 
    }; 
    document.getElementById('haha').click(); 
    } 

</script> 
</head> 
<body> 
    <input type = "button" id = "haha" value = "lol"/> 
</body> 
</html> 
相關問題