简体   繁体   English

为什么blur()无法工作?

[英]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. jquery.js在我的js文件中,我将上面的代码放在一个名为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. 当浏览器从HTML中读取脚本时,该脚本将立即运行,甚至在查看正文之前。 When the script runs, the #target element doesn't exist yet. 脚本运行时, #target元素尚不存在。

One solution would be to move the script to the bottom of <body> . 一种解决方案是将脚本移到<body>的底部。 Another would be to use jQuery's DOM ready function: 另一个方法是使用jQuery的DOM ready函数:

$(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. 但是,它将推迟在$(function () { /* code here */ } )运行该部分,直到浏览器读取所有HTML并构建其漂亮的DOM元素树为止。

It's because #target doesn't exist when that code executes. 这是因为执行该代码时#target不存在。 Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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