简体   繁体   English

JavaScript函数未使用html onclick触发

[英]Javascript function not firing with html onclick

I am battling to get my javascript function to fire when a button is clicked on my html page. 我正在努力让我的javascript函数在我的html页面上单击按钮时触发。 My html code snippet: 我的html代码段:

<!DOCTYPE html>
    <html>
        <head>
        <title>VLA SYSTEM</title>
        <a href="logout.php" onclick="logout();" style="float:right;">Logout</a>
        <script
            type ="text/JavaScript" src="logout.js"></script>

        </head>
    <body>
<form>
      <script
          type ="text/JavaScript" src="regGen.js"></script>
          <script
          type="text/JavaScript" src="submit.js"></script>
<input type="button" name="btnAssign" value="Assign Owner To Registration Number..." onclick="submit()">

My javascript code snippet: 我的javascript代码段:

function submit() {
    window.alert("Information Captured And Stored To Database!");
}

The idea is that, when the user clicks on the button, the alert should fire informing the user that information has been captured, however, I am unable to get this alert to appear. 想法是,当用户单击按钮时,警报应触发,通知用户已捕获信息,但是,我无法显示此警报。

Any advice would be greatly appreciated. 任何建议将不胜感激。

The problem is that, unintuitively, inline handlers essentially implicitly use with (this) for the element that triggered the event, and for the parent element, and so on: 问题是,unintuitively,内嵌处理器基本上是隐含的使用with (this)对触发事件的元素, 以及父元素,等等:

 <form> <input type="button" name="btnAssign" value="Assign Owner To Registration Number..." onclick="console.log(submit === document.querySelector('form').submit)" > </form> 

And form.submit is a built-in function will submit the form. form.submit是一个内置函数,将提交表单。

Either use a different function name, like doAlert : 使用不同的函数名称,例如doAlert

onclick="doAlert()"

and

function doAlert() {
  window.alert("Information Captured And Stored To Database!");
}

Or attach the listener properly using Javascript instead (inline handlers are pretty bad practice, and can result in unintuitive behavior like you're seeing): 或改为使用Javascript正确附加侦听器(内联处理程序是非常糟糕的做法,并且可能会导致不直观的行为,如您所见):

document.querySelector('input[name="btnAssign"]).addEventListener('click', submit);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM