我有链接<a href="/MyData/Delete/">
删除数据
如何使用文本are you sure
实现onclick弹出确认操作,如果选择是,则继续执行MyData / Delete上的HttpPost操作?
答案 0 :(得分:2)
<a href="/MyData/Delete/" onclick="someFunction(this, event)">
在javascript中:
function someFunction(target, event) {
if(confirm("Are you sure to delete?")) {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
// successfully deleted
}
};
xhr.open("POST", target.url, true);
xhr.send();
} else {
event.preventDefault();
}
}
更清洁的做法:
<a href="/MyData/Delete/" class="confirmlink">
document.querySelector(".confirmlink").addEventListener("click", function(event) {
if(confirm("Are you sure to delete?")) {
window.location.href = this.href;
} else {
event.preventDefault();
}
});
避免在HTML中使用内联js脚本。它会污染标记并且难以管理。