点击功能有问题

Having issue with click function

本文关键字:有问题 功能      更新时间:2023-09-26
$('#delete').click(function (e) {
    e.preventDefault();
    var result = true;
    if($('.checkbox:checked').length < 1) {
        $.notifyBar({
            cls: "error",
            html: 'At least 1 checkbox must be checked.',
            delay: 5000
        });
        result = false;
    }
    return result;
});

问题是如果一切顺利,按钮不会提交表单有什么不对吗?

e.preventDefault()的调用阻止了按钮的默认操作,即提交表单。 仅当您不希望发生提交时,才需要调用它。

$('#delete').click( function(e) {
  if($('.checkbox:checked').length<1){
    $.notifyBar({
      cls: "error",
      html: 'At least 1 checkbox must be checked.',
      delay: 5000
    });
    // Invalid, stop the submit
    e.preventDefault();
  }
})

我认为这就是您要做的:

$('#delete').click(function (e) {
    var result = true;
    if($('.checkbox:checked').length < 1) {
        $.notifyBar({
            cls: "error",
            html: 'At least 1 checkbox must be checked.',
            delay: 5000
        });
        result = false;
    }
    if(!result) e.preventDefault();
});

调用 e.preventDefault(); 将阻止提交按钮提交,无论您从函数返回什么。在我的编辑中,仅当结果为假时,才会阻止默认操作。

使用 e.preventDefault(); 将阻止表单提交,即使返回true也是如此。

您应该将其放在 onsubmit 处理程序中,而不是单击处理程序中。此外,请确保希望他们单击的按钮类型为提交:

 function doSubmit()
 {
    var result = true;
    if($('.checkbox:checked').length < 1) {
        $.notifyBar({
            cls: "error",
            html: 'At least 1 checkbox must be checked.',
            delay: 5000
        });
        result = false;
    }
    return result;
  }

 <form onsubmit="return doSubmit()">
     Checkboxes....
     <input type="submit" value="submit" />
 </form>