为什么这个JS不起作用?

时间:2013-11-30 21:50:18

标签: javascript jquery

我添加了java脚本,点击+符号时添加了一个额外的字段, 但我真的很困惑,因为这个javascript根本不起作用,就像JS根本不在页面上工作一样。

<!doctype html>    <html>
       <head>
        <meta charset="UTF-8">
        <title>Untitled Document</title>

        <script>document.cookie='resolution='+Math.max(screen.width,screen.height)+'; path=/';            </script> <!-- JS libs --> <script src="../js/libs/modernizr-2.5.3.min.js"></script> <script src="../js/libs/respond.min.js"></script> <script src="../js/libs/jquery.min.js"></script>     

<!-- scripts --> <script src="../js/jquery.easing.1.3.min.js"></script> <script src="../js/hoverIntent.js"></script> <script src="../js/general.js"></script> <!-- sliders --> <script src="../js/slides.min.jquery.js"></script> <!-- range sliders --> <script src="../js/jquery.slider.bundle.js"></script> <script src="../js/jquery.slider.js"></script> <link rel="stylesheet" href="../css/jslider.css"> <!-- custom input --> <link href="../css/customInput.css" rel="stylesheet"> <script src="../js/jquery.customInput.js"></script> <!-- datepicker --> <link href="../css/custom-theme/jquery-ui-1.8.20.custom.css" rel="stylesheet"> <script src="../js/jquery-ui-1.8.20.custom.min.js"></script>

<script type="text/javascript">    
        $("#add").click(function() {            alert("hey");
         $('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
          return false;
        });
    </script> </head>

<body>

 <a id="add">add</a></td>   <table id="mytable" width="300" border="1" cellspacing="0" cellpadding="2">   <tbody>
    <tr>
      <td>Name</td>
    </tr>
    <tr class="person">
      <td><input type="text" name="name" id="name" /></td>
    </tr>
    </tbody>   </table> </body> </html>

1 个答案:

答案 0 :(得分:2)

非常简单......运行代码时,元素不存在,并且您没有在ready处理程序中包装代码,该代码在运行之前等待所有html存在

$(function(){

  /* your code*/
})

ready() API Docs

相反,如果你的脚本就在关闭body标签之前它会按原样运行,因为元素在它触发之前就存在了