Res*_*ive 1 javascript php confirm while-loop
我有一个小问题,我用PHP while循环创建了一个删除按钮,如下所示:
while($something = mysql_fetch_array($sql_something)){
$id = $something['id']
echo '<a href="somewhere.php?id='.$id.'"><button onclick="delconfirm()">Delete</button></a>
}
Run Code Online (Sandbox Code Playgroud)
这个echo是一些内容的删除按钮.但是我首先需要用户确认删除,这是onclick="delconfirm()"进来的地方.
我的确认看起来像这样:
function delconfirm()
{
var r=confirm("Are you sure you want to delete this content?");
if (r==true){
// ...do nothing i guess? it needs to redirect using the PHP echo'd link...
}
else{
window.location = "edit.php";
}
}
Run Code Online (Sandbox Code Playgroud)
但是,无论你按取消还是确定,它都会删除它.我怎样才能解决这个问题?
把它改成这个:
while($something = mysql_fetch_array($sql_something)){
$id = $something['id']
echo '<a href="somewhere.php?id='.$id.'"><button onclick="return delconfirm();">Delete</button></a>
}
Run Code Online (Sandbox Code Playgroud)
然后你的功能:
function delconfirm()
{
return confirm("Are you sure you want to delete this content?");
}
Run Code Online (Sandbox Code Playgroud)
编辑:如果你想要一个更不引人注目的解决方案:
while($something = mysql_fetch_array($sql_something)){
$id = $something['id']
echo '<input type="button" value="Delete" data-id="$id" />';
}
Run Code Online (Sandbox Code Playgroud)
然后一些javascript来绑定事件:
function bindButtons() {
var buttons = document.getElementsByTagName("input");
for (var i = 0; i < buttons.length; i++) {
if (buttons[i].type == "button") {
buttons[i].onclick = function () {
location.href='somewhere.php?id=' + this.getAttribute("data-id");
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
并window.onload按照Ian的建议将其绑定到:
window.onload = bindButtons;
Run Code Online (Sandbox Code Playgroud)
注意:如果您使用的是jQuery,这个解决方案会更简单,更优雅.