我e.preventDefault()过去曾使用过取消click事件的方法,但是在弄清楚为什么它在这种情况下不起作用的问题上,我遇到了麻烦。我将所有标签分配到具有类名的列中,然后使用来获取对它们的引用document.queryselectorAll(.classname),然后为每个标签添加一个click事件,该事件从服务器获取值,如果未达到验证条件,则应阻止默认操作并提供用户消息。
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); } })();
它不起作用,因为响应是异步的。e.preventDefault()仅在ajax调用从服务器获得响应后才执行。你可以这样做。
我已经更新了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); }