首页 > 解决方案 > javaScript函数在第一次点击时不起作用

问题描述

单击按钮时,我正在尝试调用 JavaScript 函数(具有一些 php 代码)。但该函数第一次不起作用!我应该单击两次以使其启动。
这是我的代码...

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
function f1(id)
{
    document.getElementById("hiddenVal").value = id;
    window.alert("the function is started");
    window.alert(id);
    f2();
}
function f2()
{
    <?php
        $Biid=$_POST["hiddenVal1"];
    ?>
    window.alert("<?php echo $Biid; ?>");
}
</script>
</head>
<body>
    <form  method="post">
        <button id="2" onclick="f1(this.id)"> click me </button>
        <input type="text"  name="hiddenVal1" id="hiddenVal" /> </div>
    </form>
</body>
</html>

标签: javascriptphphtml

解决方案


问题是表单内按钮的默认行为是提交该表单因此您可以向按钮添加类型属性,这样它就不会提交表单或使用具有“preventDefault”功能的事件侦听器就像这样:

选项1:

<button id="2" type="button" onclick="f1(this.id)"> click me </button>

选项 2:

document.addEventListener('submit', function(event){
  event.preventDefault();
  f1(event.target.id);
});

推荐阅读