我不明白这个 javascript/jquery 代码是如何执行的
如果我删除第一行(alert()),下面的代码将不起作用,很明显我不需要它。我将事件绑定到的表单是使用 jquery 动态生成的。请问可能是什么问题?谢谢。
alert("");
$("#search").autocomplete('func.php');
$("#c_name").autocomplete('func.php');
$("#search").keypress(function(event) {
if (event.which === 13) {
findItem('search');
return false;
}
});
The following codes will not work if I remove the first line (alert()), and it's obvious that I don't need it. The form that I bound the events to are generated on the fly with jquery. Please what could be the problem? Thanks.
alert("");
$("#search").autocomplete('func.php');
$("#c_name").autocomplete('func.php');
$("#search").keypress(function(event) {
if (event.which === 13) {
findItem('search');
return false;
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
可能是警报提供了 jQuery 识别所需元素所需的延迟。
删除alert()并在代码周围添加以下内容:
It could be that the alert is providing the delay required for the jQuery to recognise the elements required.
Remove the alert() and add the following around the code:
该警报为表单加载提供了必要的延迟,之后将事件绑定到元素就有意义了。如果没有警报语句,代码将在表单元素实际加载之前执行。尝试使用 jquery 的 live() 函数将事件绑定到动态加载的元素。以下是如何使用它: http://api.jquery.com/live/
The alert is giving the necessary delay for the forms to get loaded, after which binding an event to an element makes sense. Without the alert statement, the code is getting executed before the form elements can actually load. Try using jquery's live() function to bind events to elements that are being dynamically loaded. Here is how to use it : http://api.jquery.com/live/
如果在动态创建搜索表单之前调用
$("#search")
,则 jQuery 查询将返回 0 个对象,并且无法将事件绑定到任何内容。对
alert()
的调用会创建一个暂停,允许在进行$("#search")
查询之前创建表单。您可以通过在使用和不使用第一个alert()
的情况下对$("#search")
的结果进行alert
来确认这一点。在尝试将任何事件绑定到搜索表单之前,您必须确保已创建搜索表单。如果这不是微不足道的事情,您可以考虑使用 jQuery 1.5+ 延迟对象 。延迟对象可用于确保在将事件绑定到搜索表单之前创建搜索表单。
If
$("#search")
is called before the search form is dynamically created, the jQuery query will return 0 objects and cannot bind the events to anything.The call to
alert()
creates a pause that allows the form to be created before the$("#search")
query is made. You can confirm this byalert
ing the results of$("#search")
with and without the firstalert()
.You must ensure the search form has been created before trying to bind any events to it. If this is not trivial to to do, you may consider using jQuery 1.5+ deferred objects. Deferred objects can be used to ensure the search form is created before binding events to it.
您需要将其包装在 $(document).ready 中:
You need to wrap this in $(document).ready a la: