Javascript,如何检查处理程序是否附加

时间:2017-09-19 13:46:45

标签: javascript javascript-events

如果我运行dispatchEvent,则在没有附加处理程序的元素上,没有任何反应。

<!DOCTYPE html>
<html>
<head>
<title>Title is required</title>
<script>
  function submitHandlers() {
    var target = document.getElementById('myForm');

    var event = new Event('submit');
    var result = target.dispatchEvent(event);

    // nothing happens because no handler is attached to target submit event
  }
</script>
</head>
<body>
  <form id="myForm">
    <input type="text" name="test" value="this is a test">
    <input type="button" value="JS Submit Handlers" onclick="submitHandlers()" >
  </form>
</body>
</html>

如何确定没有附加处理程序,然后决定手动运行document.getElementById('myForm').submit();

我需要Vanilla Js的回答......

在伪javascript中它会像

<!DOCTYPE html>
<html>
<head>
<title>Title is required</title>
<script>
  function submitHandlers() {
    var target = document.getElementById('myForm');

    if(target.hasEventListener('submit')) {
      var event = new Event('submit');
      var result = target.dispatchEvent(event);
    }   
    else {
      target.submit();
    }
  }
</script>
</head>
<body>
  <form id="myForm">
    <input type="text" name="test" value="this is a test">
    <input type="button" value="JS Submit Handlers" onclick="submitHandlers()" >
  </form>
</body>
</html>

更新

我认为这是一个Chrome问题,Firefox的行为有所不同:当你调用dispatchEvent时如果没有定义自定义处理程序,它会触发本机&#34; html&#34;提交事件(与document.getElementById('myForm').submit()相同)

0 个答案:

没有答案