在另一个函数中调用匿名函数

时间:2019-12-03 17:49:54

标签: javascript anonymous-function

如果没有填写基本表单的用户名,我正在尝试“插入”警报器,而我一直无奈地试图理解为什么未调用submit函数中的匿名函数。

JIC在我的html之上,我有一个准备好的警报块:

// print out strings that have true value
var trueValueKeys = truthTable
    .Where(kv => kv.Value)
    .Select(kv => kv.Key)
    .ToList();
foreach (var boolTuple in trueValueKeys)
{
    Console.WriteLine(boolTuple);
}

相关功能:

<div id="alerter">
</div>

是的,有一种形式叫<script> function validateForm() { var x = document.forms["formz"]["username"].value; if (x == "") { (function() { alert("whoa"); var div = document.createElement('div'); div.setAttribute('class', 'alert alert-primary alert-dismissible fade show'); div.setAttribute('role', 'alert'); div.innerHTML = document.getElementById('alertonempty').innerHTML; document.getElementById('alerter').appendChild(div); }) return false; } } </script> <script id="alertonempty" type="text/html"> <strong>SMTH went wrong</strong> Seriously wrong <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </script> 。 它确实接受了username变量,并且可以使用它(也通过警报对其进行了检查),但是未调用匿名函数。

请帮助我理解

2 个答案:

答案 0 :(得分:4)

您创建的是一个auto-executing anonymous function,为了使该功能正常运行,您需要在末尾添加第二对括号:

function validateForm() {
    var x = document.forms["formz"]["username"].value;
    if (x == "") {
      (function() {
        alert("whoa");
        var div = document.createElement('div');
        div.setAttribute('class', 'alert alert-primary alert-dismissible fade show');
        div.setAttribute('role', 'alert')
        div.innerHTML = document.getElementById('alertonempty').innerHTML;
        document.getElementById('alerter').appendChild(div);
      })();
//-----^^^^
      return false;
    }
  }

答案 1 :(得分:2)

在JavaScript中,函数声明是“悬挂的”(请参见此处:https://developer.mozilla.org/en-US/docs/Glossary/Hoisting),因此,在“ if”块中或{{1}顶部的函数声明位置实际上并不重要。 }函数-顺便说一句,它是“ JavaScript方式”的正确处理方式。

在您的情况下,您声明了匿名函数,但从未实际调用它。您的表达式将被评估为一个新的匿名函数,该函数将被愉快地吊起并且从未使用过。您应该改用以下方法:

validateForm

或者,您可以将函数声明转换为IIFE(即使在这种情况下这是非常糟糕的形式):

function validateForm() {
  function showAlert() {
    alert("whoa");
    var div = document.createElement('div');
    div.setAttribute('class', 'alert alert-primary alert-dismissible fade show');
    div.setAttribute('role', 'alert')
    div.innerHTML = document.getElementById('alertonempty').innerHTML;
    document.getElementById('alerter').appendChild(div);
  }

  var x = document.forms["formz"]["username"].value;
  if (!x) {
      showAlert();
      return false;
  }
}
相关问题