我过去曾使用e.preventDefault()
来取消点击事件,但我无法弄清楚为什么它在这种情况下不起作用。我在一个带有类名的列中分配了所有标签,然后使用document.queryselectorAll(.classname)
获取对它们的引用,然后为每个标签添加一个从服务器获取值的单击事件,如果未满足验证,则应防止默认并给予用户信息。
(function(){
const userName = document.getElementById('FullName').value;
// route
$route = '';
if (CheckDeploy(window.location.origin)) {
$route = '/x/GetReviewerCheck/';
} else {
$route = '/servername/s/GetReviewerCheck/';
}
let ReviewButtons = document.querySelectorAll('.verifyReviewer'); // .verifyReviewer = className of all a tags in table column
for (var i = 0; i < ReviewButtons.length; i++) {
const ReviewButton = ReviewButtons[i];
ReviewButton.addEventListener('click', function (e) {
let newRow = ReviewButton.parentElement.parentElement;
let AuditorName = newRow.cells[2].innerText;
let ReviewType = newRow.cells[8].innerText;
let ReviewTypeID = 0;
if (ReviewType == 'Peer Review') {
ReviewTypeID = 3;
} else if (ReviewType == 'Team Leader Review') {
ReviewTypeID = 4;
}
else if (ReviewType == 'Supervisor Review') {
ReviewTypeID = 5;
}
let id = newRow.cells[0].firstChild.getAttribute('id').split('_')[1];
$.ajax({
url: $route,
type: 'POST',
data: { userName: userName, auditor: AuditorName, reviewType: ReviewTypeID, recordID: id },
success: function (data) {
// if data is 1, prevent default
if(data == 1){
e.preventDefault();
return false;
}
}
});
}, false);
}
})();
答案 0 :(得分:2)
它不起作用,因为响应是异步的。只有在ajax调用从服务器获得响应后,才会执行e.preventDefault()。 你可以这样做。
我更新了for循环,并对更改进行了评论。请检查。
for (var i = 0; i < ReviewButtons.length; i++) {
const ReviewButton = ReviewButtons[i];
ReviewButton.addEventListener('click', function (e) {
let newRow = ReviewButton.parentElement.parentElement;
let AuditorName = newRow.cells[2].innerText;
let ReviewType = newRow.cells[8].innerText;
let ReviewTypeID = 0;
if (ReviewType == 'Peer Review') {
ReviewTypeID = 3;
} else if (ReviewType == 'Team Leader Review') {
ReviewTypeID = 4;
}
else if (ReviewType == 'Supervisor Review') {
ReviewTypeID = 5;
}
let id = newRow.cells[0].firstChild.getAttribute('id').split('_')[1];
$.ajax({
url: $route,
type: 'POST',
data: { userName: userName, auditor: AuditorName, reviewType: ReviewTypeID, recordID: id },
beforeSend:function()
{
e.preventDefault(); //Prevent default action for all instances.
},
success: function (data) {
// if data is 1, prevent default
if(data != 1){
$(this).unbind('click'); // Restores the click default behaviour if data != 1
return false;
}
}
});
}, false);
}