问题
Code below doesn't work on any browser. It's supposed to show an alert box. What am I doing wrong?
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
$('#prevlink').click(function () {
alert("Test");
});
</script>
</head>
<body>
<a id="prevlink" href="#">test</a>
</body>
</html>
回答1:
You are not wrapping the function in a ready() event. It runs before the DOM exists.
回答2:
Put it in document.ready!
回答3:
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.
回答4:
Because the javascript code executed before the html finished downloading Use this instead as your code
$(document).ready(function(){
$('#prevlink').click(function(){
alert("Test");
});
})
回答5:
Change your code to:
$(function()
{
$('#prevlink').click(function () {
alert("Test");
});
});
来源:https://stackoverflow.com/questions/3953611/am-i-going-crazy-jquery-click-doesnt-seem-to-work