简体   繁体   English

单击事件触发器,无需单击按钮

[英]click event triggers without button click

Hi i'm new to JS and could use some help. 嗨,我是JS新手,可以使用一些帮助。

So I am basically trying to send some text from a textarea to a function called inputFromText on a submit button click event, but somehow the function is being triggered before the click (when opening the html window via electron) and nothing happens when you click the button afterwards. 所以我基本上是试图在提交按钮单击事件inputFromText一些文本从文本区域发送到名为inputFromText的函数,但是以某种方式在单击之前触发了该函数(通过电子打开html窗口时),并且单击按钮。

How do I prevent this from happening? 如何防止这种情况发生?

<body>
  <form>
    <div class="form-group">
      <textarea class="form-control" rows="5" id="txa_trainingText"></textarea>
      <button type="submit" class="btn btn-default" id="btn_submit">Submit</button>
    </div>
  </form>
  <script>
    const trainingText = document.getElementById("txa_trainingText").value;
    document.getElementById("btn_submit").addEventListener("click", inputFromText(trainingText));
    function inputFromText(text) {
      ...
    } 
  </script>
</body>

I found out that when using a function without the text argument one could solve the problem by writing: 我发现使用不带文本参数的函数可以通过编写以下代码解决问题:

function inputFromText(e) {
  e.preventDefault();
  ...
}

我相信您需要将click事件处理程序包装为一个函数,因此该行应显示为:

document.getElementById("btn_submit").addEventListener("click", function() { inputFromText(trainingText)});

只需将按钮type =“ submit”更改为按钮type =“ button”

<button type="button" class="btn btn-default" id="btn_submit">Submit</button>

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

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