[英]Generate delete confirmation box
在我的应用程序中,结果显示为表格格式。
我的部分代码是,
{% for device in devices %}
<tr>
<td>{{ device.operator}}</td>
<td>{{ device.state }}</td>
<td>{{ device.tstampgps }}</td>
<td><button id='rec_delete'>Delete</button></td>
</tr>
{% endfor %}
即使我们按下删除按钮,我也需要从数据库中删除特定记录。 在此之前,我想提示一个确认框。 谁能帮我?
由于我不知道Django,这不包括删除部分,我假设您将AJAXify(执行异步请求删除)。 我也在这里单独显示$devices
和$deletes
变量作为局部变量,或多或少,这样你就可以看到如何存储引用然后从这些引用中工作(我相信这是一种比重复选择更好的做法) 。
还要注意使用:
jQuery(document).ready(function r($){
我在全局范围内使用jQuery()
,在更大的应用程序中,您应该始终保持与可能使用$()
其他库/框架冲突。 这也是一种最佳实践,您可以在该匿名函数(闭包)中使用$()
)。 最好习惯这样做,IMO。
<table>
<thead>
<tr>
<th>Operator</th>
<th>State</th>
<th>T-Stamp GPS</th>
<th> </th>
</tr>
</thead>
<tbody>
<tr class="device">
<td>Verizon</td>
<td>OK</td>
<td>033830928</td>
<td>
<button type="button" id="d001" class="delete">Delete</button>
</td>
</tr>
...
</tbody>
</table>
注意
我做了一个轻微的,但重要的变化,参考$self
,因为AJAX将运行success
处理后, this
是超出范围:
jQuery(document).ready(function r($){
var $devices = $('tr.device'),
$deletes = $devices.find('button.delete');
$deletes.click(function d(){
var $self = $(this).parents('tr.device'),
del = confirm('Delete device?');
if (del) {
// Do $.ajax() request, maybe using the
// clicked button's ID. Or you could put
// the row to delete ID on the TR element.
// And then on success of the AJAX, run:
$self.fadeOut(500, function f(){
$self.remove();
});
}
});
});
添加一个唯一的记录标识符,您可以将该标识符与DB关联到该按钮。 确认后,您使用AJAX将此标识符发送到服务器,并且删除数据库的服务器代码。 还要在重复元素上将ID更改为class,因为ID必须是唯一的
HTML
<tr>
<td>{{ device.operator}}</td>
<td>{{ device.state }}</td>
<td>{{ device.tstampgps }}</td>
<td><button class='rec_delete' data-record_id="{{ device.DB_ID }}">Delete</button></td>
</tr>
JS
$('button.rec_delete').click(function(){
/* data() method reads the html5 data attribute from html */
var record_id=$(this).data('record_id');
if( confirm( 'Are you sure') ){
$.post( 'serverPage.php', { id: record_id}, function(){
/* code to run on ajax success*/
$(this).closest('tr').remove();
})
}
})
服务器将像使用任何其他表单元素名称一样接收post密钥id
您可以向JavaScript添加click事件,如果用户选择“ok”按钮,您可以向视图发送请求以处理删除记录或其他任何内容
尝试这个:
<button id='rec_delete' onclick="return confirm('Are you sure?')">Delete</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.