我有多个提交按钮。就php而言,它们做同样的事情,将输入数据发送到数据库。但我还想在单击特定按钮时运行一些 JavaScript,但遇到了麻烦。
html:
<div id="btnGroup">
<input type="submit" id= "btn1" value="6 seats" onclick="myFunction()"/>
<input type="submit" id= "btn2" value="6 seats" onclick="myFunction()"/>
<input type="submit" id= "btn3" value="6 seats" onclick="myFunction()"/>
<input type="submit" id= "btn4" value="6 seats" onclick="myFunction()"/>
<input type="submit" id= "btn5" value="6 seats" onclick="myFunction()"/>
<input type="submit" id= "btn6" value="6 seats" onclick="myFunction()"/>
</div>
js:
function myFunction(){
alert("button clicked");
}
这个功能最终不是我想要的,它只是一个简单的测试它是否有效的东西。
如果这是相关的,与按钮关联的 php 工作正常。单击按钮后,我会转到另一个页面,该页面本质上告诉我我的 php 命令有效。理想情况下,我希望 javascript 在 php 之前运行。
最佳答案
您可以向函数发送一个参数来识别您单击的按钮:
<script>
function myFunction(el){
console.log("You clicked button with id "+el.id)
}
</script>
<div id= "btnGroup">
<input type= "submit" id= "btn1" value="6 seats" onclick="myFunction(this)"/>
<input type= "submit" id= "btn2" value="6 seats" onclick="myFunction(this)"/>
<input type= "submit" id= "btn3" value="6 seats" onclick="myFunction(this)"/>
<input type= "submit" id= "btn4" value="6 seats" onclick="myFunction(this)"/>
<input type="submit" id= "btn5" value="6 seats" onclick="myFunction(this)"/>
<input type= "submit" id= "btn6" value="6 seats" onclick="myFunction(this)"/>
</div>
关于javascript - 使用 onclick 作为提交按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47773775/