如何分离js,html和php文件

时间:2013-08-22 16:41:42

标签: php jquery

我需要帮助。 当我从create_table.php文件中抛出javascript代码,并将其添加到script.js文件中时,则无法在表中删除行。 如何分离这些文件?,有人可以帮我做这个工作吗?怎么了? THX。

index_table.html

<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
<head>
<title>Table</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="script.js"></script>
</head>
<body>
<div id="write_table"></div><br /><br />
</body>
</html>

的script.js

$(document).ready(function(){
    $.ajax({
        url:"create_table.php",
        cache: false,
        success: function(data){
            $("#write_table").html(data);
    }});
});

create_table.php

<script type='text/javascript'>
$(document).ready(function(){
  $('button.delete').click(function(e){
  var parent = $(this).closest('tr');
    $.ajax({
      cache: false,
      data: parent,
      success: function(){
      parent.fadeOut('fast', function(){
      parent.remove();
      });
    }
 });                
});
});
</script>
<?php
ini_set('display_errors', true);
error_reporting(E_ALL + E_NOTICE);
$tabela = new Tabela(); 
$header;
$data= array (      
        array ("row_1", "row_1", "row_1", null),    
        array ("row_2", "row_2", "row_2", "row_2"),
        array ("row_3", "row_3", "row_3", "row_3"),
        array ("row_4", "row_4", "row_4", "row_4")
);
$header = array("col_1","col_2","col_3","col_4"); 
$tablica1 = $tabela->NapraviTabelu($header, $data, true, true, true);
echo $tablica1;
class Tabela {
    function __construct() {
    }
public function NapraviTabelu($header, $data, $add=true, $edit=true, $delete=true){ 
$tablica1 = "<table border='3' id='tablicaId'><thead><tr>";     
  foreach ($header as $head){           
  $tablica1 = $tablica1."<th width='120px'>$head</th>"; 
  }
if($edit || $delete){
  $tablica1 .= "<th height='44px'>/*******/</th>";
 }
$tablica1 .="</tr></thead>";
  if (isset($data)){        
    foreach($data as $row){
    $tablica1 .="<tr>";
    foreach($row as $column){
  if ($column !=''){
    $tablica1 .= "<td height='44px'>$column</td>";  
  }
  else {$tablica1 .="<td></td>";}
  }                                         
if($edit || $delete)                
$tablica1 .= "<td align='right'>";
if($edit){$tablica1 .= "<button title='Edit'  type='submit'><img src='Update.png'/>  </button>";}
if($delete){$tablica1 .= "<button name='cmdEdit' class='delete' title='Delete'   type='submit'><img src='Remove.png'/></button>";}  
$tablica1 .= "</td></tr>";
}
return $tablica1 ."</table>";           
}
}

}
?>

1 个答案:

答案 0 :(得分:2)

由于create_table.php是通过ajax加载的,因此index_table.html DOM准备就绪时,其中的元素不存在。您将需要在ajax调用完成后执行此代码,或者使用如下所示的事件委派。

而不是$('button.delete').click(function(e){执行以下操作:

$('#write_table').on('click', 'button.delete', function(e){
   /* ... */
});

您可以在on documentation中了解有关事件委派的更多信息。