在数据库中,存储了许多项。当用户加载页面时,项目将作为表的行列出。为了使用户能够删除元素(行),每行还提供了一个带有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。我认为这是因为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发布于 2013-04-07 20:33:51
将其放在<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不能在其他函数中声明函数。但是你可以在里面创建变量--回调。
发布于 2013-04-07 20:42:38
既然您已经包含了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();
});
});https://stackoverflow.com/questions/15867462
复制相似问题