如何 return 来自函数的灯箱错误消息

How to return a light box error message from a function

我创建了一个基本的表单验证脚本,我想 return 将错误消息作为灯箱显示,而不是使用 alert() 消息。我喜欢 featherlight.js 的外观,但我不知道如何从函数中 return 它?任何其他建议都将非常适用。提前致谢。

The featherlight.js repo

function validate() {          
  var name = document.forms['userForm']['fname'].value;
  if (name == null || name == '') {
    alert('Please enter your first name');
 return false;
  } 
}
<label for="first-name">First Name: </label><br>
<input name="fname" type="text" /><br>
<button onclick="validate()">Submit Form</button>

基本上,你不能"return"它。您可以做的是当您的条件匹配时触发灯箱事件,如下所示:

function validate() {                                   
    var name = document.forms['userForm']['fname'].value;
    if (name == null || name == '') {
        $.featherlight($content, $configuration); // Lightbox for wrong validation
        return false;
    } else {
        $.featherlight($content, $configuration); // Lightbox for successful validation
        return true;
    }
}

当然,您需要根据需要修改 $content 和 $configuration 变量,如下所述: https://github.com/noelboss/featherlight/

我知道这有点晚了,但我想我知道你想要什么。我自己也做过类似的事情,所以我把它放在这里以防它对任何人有帮助。

我创建了一个函数,以便您可以在其他地方重复使用它以及关闭灯箱的“确定”按钮。

function customAlert(message = '') {
  var alertBox = $(document.createElement('div'));
  alertBox.html('<h3>'+message+'</h3><p><a class="featherlight-close">OK</a></p>');
  $.featherlight(alertBox);
}


function validate() {
  var name = document.forms['userForm']['fname'].value;
  if (name == null || name == '') {
    customAlert('Please enter your first name');
    return false;
  } 
}