我一直在到处寻找一种方法来做到这一点。
我使用PHP while循环从数据库中获取一些变量:
<?php while ($row = mysql_fetch_array($query)) {
$id = $row["ID"];
?>
<script type="text/javascript">
<!--
function go_there()
{
var id= "<?php echo $id ?>"
var where_to= confirm("Are you sure you want to delete?");
if (where_to== true)
{
window.location="index.php?p=delete&id=" + id;
}
else
{
}
}
//-->
</SCRIPT>
<td><form><INPUT TYPE="button" value="Go!" onClick="go_there()"></form></td></tr>
<? } //end while
?>有时我会得到10个结果,然后让10个继续!臀部。但当我进入删除页面时,无论我按下哪一个底部,$is变量都是off,因为它与上一个结果相同。
有什么办法解决这个问题吗?这样我就得到了确认框,同时仍然保留了要删除的正确id?
发布于 2013-03-19 00:15:06
您将为每个条目创建一个名为"go_there“的全局函数,因此将只保留最后一个条目。取而代之的是,只创建一个函数,并从按钮的属性中获取"id“值。
function go_there(button)
{
var id= button.getAttribute("data-id");
var where_to= confirm("Are you sure you want to delete?");
if (where_to== true)
{
window.location="index.php?p=delete&id=" + id;
}
}然后:
<INPUT TYPE="button" value="Go!" onClick="go_there(this)" data-id="<?php echo $id ?>">发布于 2013-03-19 00:15:21
在我看来,你在你的循环中创建了你的javascript函数,所以它只触发其中的一个(你创建了多个同名的函数。它应该如何知道要使用哪一个)。您应该创建一个javascript函数,并将id作为参数传递给它。
<script type="text/javascript">
function go_there(id)
{
var where_to= confirm("Are you sure you want to delete?");
if (where_to== true)
{
window.location="index.php?p=delete&id=" + id;
}
else
{
}
}
</SCRIPT>
<?php while ($row = mysql_fetch_array($query)) {
$id = $row["ID"];
echo '<td><form><INPUT TYPE="button" value="Go!" onClick="go_there(<?php echo $id; ?>)"></form></td></tr>'
} //end while
?>发布于 2013-03-19 00:17:54
总体而言,这是一种很糟糕的方式。您应该避免内联wrtiting处理程序,除非在特定情况下这是唯一的方法。如果你给问题中的元素附加一个处理程序会更好(working fiddle -对于火狐来说无论如何...):
<!-- output our inputs with the id value in an attribute data-id-value -->
<?php while ($row = mysql_fetch_array($query)): $id = $row["ID"]; ?>
<td><form><INPUT class="go-button" TYPE="button" value="Go!" data-id-value="<?php echo $id ?>"></form></td></tr>
<?php endwhile; ?>
<script type="text/javascript">
var goButtons = document.querySelectorAll('input.go-button'), // select all out buttons
// define our handler function
goThere = function (event) {
// get the id the we encoded from php from our data attr
var id = event.target.getAttribute('data-id-value');
if(confirm('Are you sure you want to delete?')) {
// if confirm is true then redirect to the delete url
window.location = "index.php?p=delete&id=" + id;
}
};
// loop over the buttons and attach the handler
for (var i = 0; i < goButtons.length; i++) {
goButtons[i].addEventListener('click', goThere);
}
</script>这里的问题是,这不一定是跨浏览器的。这通常是人们使用jQuery或类似库的原因之一,这样他们就不必标准化dom查询和侦听器连接。
https://stackoverflow.com/questions/15481359
复制相似问题