You're trying to access the element before it exists (JavaScript is run inline with HTML parsing/rendering). You can either use the ready
event that jQuery provides as Pekka and Mike pointed out, or just make sure you're trying to access the element after it exists:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
</head>
<body>
<a id="prevlink" href="#">test</a>
<script type="text/javascript">
// By this time we get here, it exists.
$('#prevlink').click(function () {
alert("Test");
});
</script>
</body>
</html>
The former (using a ready
event or similar) is more "unobtrusive" and that's very useful when you're dealing with large teams, where your HTML designers and JavaScript coders are usually different people. The latter happens sooner (no small gap in time after the link appears and before you hook the click event), and so is what the Google Closure team recommend for hooking up element handlers.
Even when using the second method, you can keep your JavaScript and HTML reasonably separated, by ensuring that the script
tag is just a call to set up the element and has no actual logic of its own.