猿问

如何激活 JavaScript 按钮,就像用户单击它一样?

如何激活 JavaScript 按钮,就像用户单击它一样?我可以运行 javascript 代码来激活按钮吗?(假设我还不知道按钮中的代码,并且我在一个随机网站上,我无法更改现有代码)


<!DOCTYPE html>

<html>

  <body>

    <form action="aaa.php">

      <input type="text" />

      <input id="button" type="submit" />

    </form>

    <script>

      var btn = document.getElementById("button");

      //is there anything like: btn.click?

    </script>

  </body>

</html>


慕的地10843
浏览 70回答 3
3回答

凤凰求蛊

<!DOCTYPE html><html>&nbsp; <button id="button"onclick="myFunction()">b</button>&nbsp; <!--creates the button-->&nbsp; <script>&nbsp; &nbsp; var btn = document.getElementById("button");&nbsp; &nbsp; btn.click();&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; function myFunction(){&nbsp; &nbsp; &nbsp; &nbsp;alert('working');&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; </script></html>

茅侃侃

如前所述,您可以将 HTML 和 javascript 分开。样本。<!DOCTYPE html><html><body>&nbsp; &nbsp; <button id="button">Click Here</button>&nbsp; &nbsp; <button onclick="onClickBtn(this)">Click Here 2</button>&nbsp; &nbsp; <!--creates the button-->&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; var btn = document.getElementById("button");&nbsp; &nbsp; &nbsp; &nbsp; btn.addEventListener("click", (event) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("Hi")&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; function onClickBtn(event) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("Btn 2")&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </script></body></html>

米琪卡哇伊

这是你可以处理它的一种方法,从你的程序中调用一个特定的函数onClick<!DOCTYPE html><html>&nbsp; <button id="button" onclick="clickButton()">b</button>&nbsp; <!--creates the button-->&nbsp; <script>&nbsp; &nbsp; function clickButton() {&nbsp; &nbsp; &nbsp; &nbsp;alert("hello!");&nbsp; &nbsp; }&nbsp; </script></html>为了更直接地回答您的问题,这是您可以做到的一种方法document.getElementById('button').onclick=function(){/* some code */}
随时随地看视频慕课网APP

相关分类

Html5
我要回答