<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>
jquery.js在我的js文件中,我把上面的代码放在一个名为test.html的文件中。当我单击第一个输入文本框然后单击其他位置。没有弹出警报框?
答案 0 :(得分:3)
当浏览器在HTML中读取脚本时,脚本立即运行,即使在查看正文之前也是如此。当脚本运行时,#target
元素尚不存在。
一种解决方案是将脚本移到<body>
的底部。另一种方法是使用jQuery的DOM就绪函数:
$(function() {
$('#target').blur(function() {
alert('welcome,boy.');
});
});
在这种情况下,您仍然可以将脚本放在头部,脚本本身也会运行。但是,它会推迟在$(function () { /* code here */ } )
包装器中运行该部件,直到浏览器读取了所有HTML并构建了其优秀的DOM元素树。
答案 1 :(得分:3)
这是因为代码执行时#target不存在。试试这个:
<script type="text/javascript">
$(function(){
$('#target').blur(function() {
alert('welcome,boy.');
});
});
</script>