开发者

why the blur() can't work?

      <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>test</title>
     <script type="text/javascript" src="开发者_如何学Cjs/jquery.js"></script>
     <script type="text/javascript">
   $('#target').blur(function() {
 alert('welcome,boy.');
  })
</script>
   </head>

 <body>
  <form>
<input id="target" type="text" value="Field 1" />
 <input type="text" value="Field 2" />
  </form>
 <div id="other">
  Trigger the handler
</div>

</body>
</html>

the jquery.js is in my js file, i put the above code in a file named test.html. when i click the first input textbox then click at other place. there is no popup an alert box?


The script runs immediately when the browser reads it in the HTML, which is before it even looks at the body. When the script runs, the #target element doesn't exist yet.

One solution would be to move the script to the bottom of <body>. Another would be to use jQuery's DOM ready function:

$(function() {
    $('#target').blur(function() {
        alert('welcome,boy.');
    });
});

In that case, you could still put the script at the head, and the script itself would run. However, it would put off running the part inside the $(function () { /* code here */ } ) wrapper until the browser has read all of the HTML and has built its nice tree of DOM elements.


It's because #target doesn't exist when that code executes. Try this:

<script type="text/javascript">
  $(function(){
    $('#target').blur(function() {
      alert('welcome,boy.');
    });
  });
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜