如何在JavaScript中取消按钮单击事件?

m4pnthwp  于 2023-02-15  发布在  Java
关注(0)|答案(2)|浏览(268)

我试了两种方法:

$(document).ready(function()
{
    $('input[type=button]').on('click', function(evt){
        if ($(this).val() == 'Close')
          return true;
        var totalHours = 999; // here I am computing a total number of hours but that is irrelevant to my question
        var reportedTotalHours = parseFloat($("#TotalHours").text());
        var difference = Math.abs(totalHours - reportedTotalHours);
        if (difference >= 0.25) // discrepancy must be less than a quarter hour
        {
          alert("Total of hours for each activity must equal " + reportedTotalHours + ".");
          evt.preventDefault();
          return false;
        }
        return true;
    });
});

return false;应该取消按钮单击,evt.preventDefault();也应该取消按钮单击,但这两种操作都不起作用。单击按钮时会发生表单提交的情况,但我希望在小时数差异小于0.25之前阻止表单提交。

b4lqfgs4

b4lqfgs41#

尝试将input[type=button]更改为button标记,然后在条件合适时在onclick回调中提交表单。
在一些浏览器中,如果没有input[type=submit]元素,input[type=button]元素将提交表单。

jvlzgdj9

jvlzgdj92#

const prev = document.querySelector('.prev')
let current = 2
if(current >= 1) {
        prev.disabled = false
    }else {
        prev.disabled = true
    }
<button class="prev">Prev</button>

相关问题