简体   繁体   中英

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="js/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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM