Am I going crazy? jQuery .click() doesn't seem to work

谁说胖子不能爱 提交于 2020-02-04 04:49:44

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!