在数据库中,存储了许多项目。当用户加载页面时,项目将列为表的行。为了使用户可以删除元素(行),每行还提供了一个“删除项”按钮,该按钮上附加了onclick事件。这是生成表的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。我相信这是因为DOM不知道PHP返回的remove_item()函数。

如何纠正?

完整的标记在这里

 <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


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

关于php - 将Javascript事件添加到PHP中的按钮,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15867462/

10-11 21:51
查看更多