Cha*_*alG 3 html javascript onclick
在摆弄 HTML 代码时,我想到了一件令人难以置信的事情。看看代码:-
<form class="index-form" name="LoginForm">
<div class="index-input">
<button onclick="myFunction();">Login</button>
</div>
</form>
<script>
function myFunction(){
window.location = "https://blahblah.com/auth/?client_id=fdsgsnlr";
};
</script>
Run Code Online (Sandbox Code Playgroud)
这只是添加了一个“?” 在我的网址中,什么也没做。但是当我从父表单元素中释放按钮元素时,它工作得很好。我知道我所做的只是胡说八道,但仍然知道它是如何以及为什么发生的吗?
当你的按钮写在里面<form>然后onclick在按钮上调用事件处理程序之后,你的表单被提交。由于action您的<form>元素中没有定义任何属性,因此默认设置是GET使用表单中的任何给定命名输入向当前页面发出请求,因为您没有任何属性,所以您只会得到“?”。
现在,如果您从onclick事件处理程序返回 false ,则表单不会被提交并且您的 window.location 代码有效。
更新代码应该是 -
<form class="index-form" name="LoginForm">
<div class="index-input">
<button onclick="myFunction(); return false;">Login</button>
</div>
</form>
<script>
function myFunction(){
window.location = "https://blahblah.com/auth/?client_id=fdsgsnlr";
};
</script>
Run Code Online (Sandbox Code Playgroud)
此外
<button>默认为<button type="submit">which 提交父表单,您可以改为使用<button type="button">which 不提交表单。
| 归档时间: |
|
| 查看次数: |
2675 次 |
| 最近记录: |