javascript - 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>
解决方案
问题是表单内按钮的默认行为是提交该表单因此您可以向按钮添加类型属性,这样它就不会提交表单或使用具有“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);
});
推荐阅读
- python - 获取一维数组 Numpy Python 的元素
- c# - BehaviorSubject 元素的顺序与预期输出相反
- jenkins - 带有 pipeline-github 插件的 Jenkins 多分支管道:首次运行的限制
- sql-server - Outlook、VBA 宏、到 SQL Server Express 的连接字符串
- subquery - 即使我将限制设置为 5,如何在列中显示重复的结果?
- c - 在 C 中集成复合函数
- javascript - 如何从另一个访问堆栈导航器的导航道具
- javascript - 此代码是否用于确定圆和线段是否相交正确?
- typescript - 作为道具传递与提取缓存 Apollo 客户端 Nextjs
- node.js - Typeorm 交易不发布