2012-10-07 33 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 - 没问题,很高兴我可以帮助:)您可以选择“文档”,因为它是在标记被解析和呈现之前首先创建的。这是有道理的,因为它是任何页面的根对象。 –