2012-10-07 106 views
1

我一直在試圖學習如何在PHP中使用jQuery AJAX。JQuery選擇器似乎無法正常工作,除非在選擇文檔時

我的問題是,每當我選擇除document之外的任何其他元素,似乎沒有任何工作。我想要的只是在按下提交按鈕後無法加載頁面,無濟於事。

我試過使用jQuery而不是$,仍然沒有運氣。

我老實說不知道我在做什麼,而且我試過尋找這個解決方案的小時數。

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> 
<script> 
    $("p").click(function() { 
     alert('test'); 
    }); 
    $("form").submit(function() { 
     alert('test'); 
     return false; 
    }); 
</script> 
<title>Insert title here</title> 
</head> 
<body> 
    <form action="process.php" method="post"> 
     Inputs:<br /> 
     <textarea rows="15" cols="60" id="input" name="input">Some text... 
     </textarea><br /><br /> 
     Start: 
     <input type="text" id="start" name="start" /> 
     End: 
     <input type="text" id="end" name="end" /><br /> 
     <input type="submit" id="submit" name="submit" value="Submit"> 
    </form> 
    <p id="output">Output: Some Random Text</p> 
</body> 
</html> 

回答

2

您正試圖在加載之前選擇元素。一旦文件被加載,使用document ready事件來運行你的代碼。

<script> 
    $(function() 
    { 
     $("p").click(function() { 
      alert('test'); 
     }); 
     $("form").submit(function() { 
      alert('test'); 
      return false; 
     }); 
    }); 
</script> 
5

的頁面的其餘部分加載之前目前JavaScript運行。爲了解決這個問題,將你的腳本到頁面底部(收盤</body>標記之前),或者綁定一個事件處理到DOM ready事件與jQuery的.ready() method

$(document).ready(function() { 
    // Your code in here 
}); 

//or, use the shorthand form: 

$(function() { 
    // Your code here 
}); 

旁註

我試過使用jQuery而不是$,仍然沒有運氣。

jQuery$之間沒有區別。兩者都只是一個標識符,可以引用同一個對象。使用$通常會更容易(僅僅因爲它更短),除非您使用的另一個庫除了需要標識符的jQuery(例如PrototypeJS)之外,在這種情況下,您可以告訴jQuery放棄對$標識符的控制權.noConflict()方法。

+0

謝謝!現在正在工作。我可以問爲什麼選擇文件仍然工作,即使它沒有準備好? – Chad

+0

@Chad - 沒問題,很高興我可以幫助:)您可以選擇「文檔」,因爲它是在標記被解析和呈現之前首先創建的。這是有道理的,因爲它是任何頁面的根對象。 –