javascript html5 / jquery - 单击事件未注册 html 按钮标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7192017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
html5 / jquery - click event not registering for html button tag
提问by mheavers
I am trying to validate a form, but I can't get any code to execute when my button is clicked. Here's my code:
我正在尝试验证表单,但单击按钮时无法执行任何代码。这是我的代码:
<div id="vehicle_form">
<form method="post" name="emailForm" action="">
<input class="dField" id="dfEmail" type="email" name="email" value="Email" onfocus="clearInput(this);" onblur="restoreInput(this)"><br/>
<input class="dField" id="dfName" type="text" name="firstname" value="First Name" onfocus="clearInput(this);" onblur="restoreInput(this)"><br/>
<input class="dField" id="dfLast" type="text" name="lastname" value="Last Name" onfocus="clearInput(this);" onblur="restoreInput(this)"><br/>
<button type="button" id="dSubmit">Submit</button>
</form>
</div>
$('#dSubmit').click(function(){
console.log('click');
});
回答by Rion Williams
You need to ensure that your jQuery is wrapped in a <script>
tag, and ensure that the function is being loaded, perhaps by a $(document).ready()
function, as shown below:
您需要确保您的 jQuery 被包装在一个<script>
标签中,并确保正在加载该函数,可能是由一个$(document).ready()
函数加载,如下所示:
<script type='text/javascript'>
$(document).ready(function(){
//Your Click event
$('#dSubmit').click(function(){
console.log('click');
});
});
</script>
回答by alexander farkas
Actually the code stays wrong. A form can be often submitted by hitting enter inside of a textfield. If you want to make it right you should use the submit event.
实际上代码仍然是错误的。通常可以通过在文本字段内按 Enter 来提交表单。如果你想使它正确,你应该使用提交事件。
<script>
$(function(){
$('#vehicle_form > form').submit(function(){
console.log('submit');
});
});
</script>