为什么在这种情况下无法启动脚本

时间:2012-02-17 05:38:05

标签: jquery

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="plugin/easyui/themes/gray/easyui.css">
    <link rel="stylesheet" type="text/css" href="plugin/easyui/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="style/main.css">
    <script type="text/javascript" src="plugin/easyui/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$("#closeMe").click(function() {
    $(this)
        .parent()
        .slideUp();
});
</script>
</head>

<body>
<div id="rem">
<span id="closeMe"><img src="http://www.cespage.com/silverlight/appbar/dark/close.png"></span>
<p>Please read the documentation.For updates please follow our blog, tweets or become a fan.</p>
</div>
</body>
</html>

这是一个带有关闭按钮的简单框,一旦按下,它就会向上滑动。但是,当我测试它并按下按钮时,没有反应。问题是什么?谢谢。

3 个答案:

答案 0 :(得分:1)

您的初始化代码应该在$(document).ready()调用中,如下所示:

<script type="text/javascript">
$(document).ready(function(){
    $("#closeMe").click(function() {
        $(this)
            .parent()
            .slideUp();
    });
});
</script>

按原样,它试图在#closeMe项目存在之前运行。 $(document).ready()确保它等待DOM准备好。

答案 1 :(得分:0)

将代码包装在就绪处理程序

$(function(){    
 $("#closeMe").click(function() {
    $(this)
        .parent()
        .slideUp();
   });    
 });

或者在文档末尾移动脚本,如

<body>
<div id="rem">
<span id="closeMe"><img src="http://www.cespage.com/silverlight/appbar/dark/close.png"></span>
<p>Please read the documentation.For updates please follow our blog, tweets or become a fan.</p>
</div>
</body>
<script type="text/javascript">
$("#closeMe").click(function() {
    $(this)
        .parent()
        .slideUp();
});
</script>

答案 2 :(得分:0)

你需要包装你的jquery函数,使其在页面完成时起作用:

$(function() {

   $("#closeMe").click(function() {
       $(this).parent().slideUp();
   });

}