设置一个按钮监听器

问题描述

我的网站上的按钮有问题。我已经从同事那里拿来了,想更改按键的功能

目前,这可以直接在HTML中解决。看起来像这样:

<table class="formButtons">
  <tr>
    <td>
      <form method="post">
        <p> <input name='"Variable".allowStart' value="1" type="hidden"> </p>
        <p> <input class="Start" value="Start" type="submit"> </p>
      </form>
    </td>
    <td>
      <form method="post">
        <p> <input name='"Variable".allowStart' value="0" type="hidden"> </p>
        <p> <input class="Stop" value="Stop" type="submit"> </p>
      </form>
    </td>
  </tr>
</table>

按“开始”或“停止”按钮时,将重新加载整个页面。我不要那个。

如您所见,我的变量'“ Variable” .allowStart“'被调用并设置为value = 1。现在我想在Javascript中将变量的值设置为1,但我不知道如何。你帮我? 而且,请给出详细的答案,我是编程的初学者。

其他信息:

'"Variable".allowStart' 

是我从西门子PLC获得的变量。

它的工作方式如示例所示。我要做的就是将变量作为注释添加到HTML文件中。像这样:

<!-- AWP_In_Variable Name='"Variable".allowStart' -->

解决方法

我不理解您的'"Variable".allowStart',但是如果您能够在javascript中使用它,那么您可以继续此答案。

要阻止StartStop按钮重新加载页面,您可以使用input来阻止preventDefault()元素的默认行为,并从在那里。

为此查看修改后的HTML和javascript

window.onload = function (){
  var start = document.getElementById('Start');
  var stop = document.getElementById('Stop');
  
  start.onclick = function (e) {
      e.preventDefault();

      //add desired code here
      console.log('Clicked Start');
  }

  stop.onclick = function (e) {
      e.preventDefault();

      //add desired code here
      console.log('Clicked Stop');
  }
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <title>Weird Buttons</title>
</head>
<body>
  <table class="formButtons">
  <tr>
    <td>
      <form method="post">
        <p> <input name='"Variable".allowStart' value="1" type="hidden"> </p>
        <p> <input id="Start" class="Start" value="Start" type="submit"> </p>
      </form>
    </td>
    <td>
      <form method="post">
        <p> <input name='"Variable".allowStart' value="0" type="hidden"> </p>
        <p> <input id="Stop" class="Stop" value="Stop" type="submit"> </p>
      </form>
    </td>
  </tr>
</table>

</body>
</html>