为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕的地10843 2023-10-24 21:15:39
如何激活 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>
查看完整描述

3 回答

?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

<!DOCTYPE html>

<html>

  <button id="button"onclick="myFunction()">b</button>

  <!--creates the button-->

  <script>

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

    btn.click();

    

    function myFunction(){

       alert('working');

       }

  </script>

</html>


查看完整回答
反对 回复 2023-10-24
?
茅侃侃

TA贡献1842条经验 获得超21个赞

如前所述,您可以将 HTML 和 javascript 分开。


样本。


<!DOCTYPE html>

<html>


<body>

    <button id="button">Click Here</button>

    <button onclick="onClickBtn(this)">Click Here 2</button>

    <!--creates the button-->

    <script>

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

        btn.addEventListener("click", (event) => {

            alert("Hi")

        })

        function onClickBtn(event) {

            alert("Btn 2")

        }

    </script>

</body>

</html>


查看完整回答
反对 回复 2023-10-24
?
米琪卡哇伊

TA贡献1998条经验 获得超6个赞

这是你可以处理它的一种方法,从你的程序中调用一个特定的函数onClick


<!DOCTYPE html>

<html>

  <button id="button" onclick="clickButton()">b</button>

  <!--creates the button-->

  <script>

    function clickButton() {

       alert("hello!");

    }


  </script>

</html>

为了更直接地回答您的问题,这是您可以做到的一种方法


document.getElementById('button').onclick=function(){/* some code */}


查看完整回答
反对 回复 2023-10-24
  • 3 回答
  • 0 关注
  • 48 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信