在PHP中为按钮添加Javascript事件


Add Javascript event to button in PHP

在数据库中,存储了许多项。当用户加载页面时,这些项将作为表的行列出。为了使用户能够删除元素(行),每行还提供一个带有onclick事件的"remove item"按钮。下面是生成表的PHP部分。

for ($i=0; $i<$num_books; $i++)
{
    $book  = mysql_fetch_row($classics);
    $shop .= "<tr>'n";
    $shop .= "<td>".$book[0]."</td>'n";
    $shop .= "<td><input type='button' onclick='remove_item()' value='Remove' /></td>'n";
    $shop .= "</tr>'n";
}

remove_item()函数是在JQuery外部定义的(见下文)。

然而,现在点击按钮导致错误:ReferenceError: Can't find variable: remove_item。我认为这是因为PHP返回的remove_item()函数不为DOM所知。

如何纠正?

完整的标记在这里

 <html>
     <head>
     <script type='text/javascript'
             src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js">
     </script>
     <script type="text/javascript"
             src="../behaviour/interactions.js">
     </script>
     </head>
     <body>
         <h1>Publications database</h1>
         <div id="items"></div>
     </body>
 </html>

完整的 interactions.js脚本在这里

$('document').ready(function()
{
    // Path to MySQL configuration.
    var server = '../server/'
    var data   = '../data/'
    function mysql_connection_setup()
    {
        $.get(data + 'mysql_connection_setup.php');
    }
    function populate()
    {
        $.get(server + 'shop.php', cb);
    }
    function remove_item()
    {
        console.log("Remove item.");
    }
    // Generic AJAX callback.
    function cb(response)
    {
        $('#items').html(response);
    }
    mysql_connection_setup();
    populate();
}); // End ready

把这个放到<head>标签中:

<script>
  function remove_item()
  {
      console.log("Remove item.");
      // Fancy AJAX call to manipulate database.
  }
</script>

通过这样做,可以全局访问该函数。或者,至少,你必须声明你的函数before调用它们。

好的,这应该是解决方案:首先,全局声明变量。

<head>
  <script>
    var mysql_connection_setup, populate, remove_item, cb ;
  </script>
</head>

然后给变量赋函数:

$('document').ready(function()
{
    // Path to MySQL configuration.
    var server = '../server/'
    var data   = '../data/'
    mysql_connection_setup = function()
    {
        $.get(data + 'mysql_connection_setup.php');
    }
    populate = function()
    {
        $.get(server + 'shop.php', cb);
    }
    remove_item = function()
    {
        console.log("Remove item.");
    }
    // Generic AJAX callback.
    cb = function(response)
    {
        $('#items').html(response);
    }
    mysql_connection_setup();
    populate();
}); // End ready

不能在其他函数中声明函数。但是您可以在内部创建变量回调。

既然你已经包含了jQuery,考虑使用它自己的click和文档准备函数。

我将把PHP代码改成这样:
for ($i=0; $i<$num_books; $i++)
{
    $book  = mysql_fetch_row($classics);
    $shop .= "<tr>'n";
    $shop .= "<td>".$book[0]."</td>'n";
    $shop .= "<td><input type='button' class='myClass' value='Remove' /></td>'n";
    $shop .= "</tr>'n";
}

在HTML文档的<head>部分,我会添加这个:

$(document).ready(function(){
    $('.myClass').click(function(){
       console.log("Remove item."); //or call directly remove_item();
    });
});