2011-09-24 188 views
5

所以我有這個代碼應該監聽點擊#button,但它不會工作,並且讓我瘋狂!jQuery監聽器單擊不工作

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> 
<script type="text/javascript"> 
    $('#button').click(function() { 
     alert('OK!'); 
    }); 
</script> 

和HTML:

<input id="button" type="button" value="OK" /> 

這是奇怪的。歡迎任何幫助!

回答

13

編寫代碼的document.ready功能

<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"> 
</script> 
<script type="text/javascript"> 
$(document).ready(function() { 
    $('#button').click(function() { 
     alert('OK!'); 
    }); 
}); 
</script> 


OR 
<script type="text/javascript"> 
    function on_click() { 
      alert("OK !!"); 
    } 
    $(document).ready(function() { 
     $("#button").click(on_click); 
    }); 
</script> 

希望你從這個

+0

ca ñ我將這個邏輯應用於整個'functions.js'文件? –

+0

是的,你也可以申請在js文件裏面 –

+0

試過在我的函數文檔中包裝一切$(document).ready(function(){FUNCTIONS etc}); 不起作用。 –

2

這裏的一些想法裏面的代碼應該是什麼樣子:

<script type="text/javascript" 
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"> 
</script> 
<script type="text/javascript"> 
    // Now that jquery is include, place the code to wire up the button here 
    $(function(){ 
     // Once the document.onload event fires, attach the click 
     // event handler for the button 
     $('#button').click(function() { 
      alert('OK!'); 
     }); 
    }); 
</script> 
<input id="button" type="button" value="OK" /> 

這裏是jQuery的文檔是涉及此: http://docs.jquery.com/How_jQuery_Works

+0

由於它包含更好的解釋,說明爲什麼原始代碼不起作用,並指向詳細信息如何$(function(){});作品。 – gcastro