简体   繁体   English

jQuery事件处理程序不起作用

[英]jQuery event handler not working

I can bind a jquery event to this element like: 我可以将jquery事件绑定到此元素,如:

<script type="text/javascript">
$('#new_key').ready(function() {
 alert('Handler for .submit() called.');
 return false;
});

It works as expected 它按预期工作

but if i do: 但如果我这样做:

<script type="text/javascript">
$('#new_key').submit(function() {
  alert('Handler for .submit() called.');
  return false;
});

it dont work. 它不工作。 does anybody knows why? 有谁知道为什么? what am i missing? 我错过了什么?

You need to do: 你需要这样做:

$(function() { //equal to $(document).ready() {
  $('#new_key').submit(function() {
    alert('Handler for .submit() called.');
    return false;
  });
});

The form may not be ready to be bound to when you're calling, so you need to wrap it to execute and rig up the handler when the document is ready. 当您调用时,表单可能还没有准备好绑定,因此您需要将其包装起来以便在文档准备好时执行并装配处理程序。

$.ready() , if used, ought to be used on the document to indicate the DOM has been fully-loaded. 如果使用$.ready() ,则应该在文档上使用它来表明DOM已经完全加载。

$(document).ready(function(){

  $("#new_key").submit(function(e){
   e.preventDefault();
   alert("Submit called!");
  });

});​

Online Demo: http://jsbin.com/ojaqo3/edit 在线演示: http//jsbin.com/ojaqo3/edit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM