2012-05-30 41 views
0

我想了解jQuery中的事件綁定。我寫了一個簡單的代碼如下:jQuery綁定:函數在事件之前運行

<html> 

<script language="javascript" src="jquery.js"></script> 

<body> 
<form> 
<input type="button" name="bu1" value="click me"> 
</form> 
</body> 

<script language="javascript"> 
jQuery("input[type='button']").bind('click',alert('Hello')); 
</script> 


</html> 

當我運行該頁面時,警報發生在加載而不是當我單擊按鈕時。任何人都可以幫助我瞭解我錯在哪裏?

+0

你必須提供一個函數,所以把你的警報打包到函數中(){alert('hello');} –

+1

你正在調用函數'alert'並將結果傳遞給'.bind' ...'functionName(arg1 ,arg2,...)立即調用函數 – Esailija

回答

3
jQuery("input[type='button']").bind('click', function() { 
    alert('Hello'); 
}); 

您需要傳遞一個函數,而不是調用它。所以在上面的代碼中,我添加了一個匿名函數來調用alert。

+0

謝謝。有效。但如果我需要給一個函數,然後如果我創建函數說函數display(){alert(「hello」);}然後將此函數作爲jQuery(「input [type ='button']」)。bind '點擊',顯示());仍然在頁面加載時調用它。傳遞函數和調用它有什麼區別? – codingsplash

+0

如果你喜歡'jQuery(「input [type ='button']」)。bind('click',display())''然後'display'函數將被立即調用並執行並且會返回undefined if你不會自己返回其他東西,並且'undefined'將被設置爲你的事件處理程序。它期望在事件發生時稍後調用函數引用。 –

+2

我剛剛得到它。我正在使用函數調用而不是函數引用。我多麼愚蠢!現在當我鍵入jQuery(「input [type ='button']」)。bind('click',display);它工作正常。謝謝大家! – codingsplash

0

你應該通過函數作爲第二個參數

jQuery("input[type='button']").bind('click', function() { 
    alert('Hello') 
}); 

否則,JavaScript的運行alert('Hello')bind函數的第二個參數中獲得價值,這樣就可以獲得警報在窗口中顯示出來。

0
<script language="javascript"> 
jQuery(function(){ 
     jQuery("input[type='button']").bind('click',function(){ 
     alert('Hello') 
    }) 
}) 

</script> 

做內部

Jquery(function(){ 

}) 

和編輯

jQuery("input[type='button']").bind('click',function(){ 
      alert('Hello') 
     }) 
0

呀,包起來的功能,我還要補充的event.preventDefault(),以及:

jQuery("input[type='button']").bind('click', function(e) { 
    e.preventDefault();   
    alert('Hello'); 
}); 

Rob

相關問題