功能和文档准备好的jQuery [英] jquery on function and document ready

查看:93
本文介绍了功能和文档准备好的jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery on()函数将onclick函数附加到一组在我的网站上定位如下:

I use the jQuery on() function to attach an onclick function to a set of anchors in my website as follows:

<ul>
  <li>First <a href='#' title='delete' class="itemDelete">x</a></li>
  <li>Second <a href='http://www.repubblica.it' title='delete' class="itemDelete">x</a></li>
  <li>Third <a href='#' title='delete' class="itemDelete">x</a></li>
</ul>​

<script type="text/javascript">
$(document).on('click', '.itemDelete', function(e) {
    $(this).closest('li').remove();
    e.preventDefault();
});
</script>

我应该在以下代码段中插入javascript代码吗?

Should I insert the javascript code in the following block?

$(document).ready(function() {
  ...
});

如果是,为什么?

推荐答案

在任何情况下,这段代码都不需要完全解析文档内容,因为您使用的是始终存在的document.作为第二个参数传递的选择器不会以任何方式用于检索元素,因此dom不需要为此做好准备.

That piece of code does not require document content to be fully parsed in any case because you are using document which always exists. The selector passed as second argument is not used in any way to retrieve elements, so the dom doesn't need to be ready for this.

如果以上情况并非如此,则您将无法首先拨打$(document).ready.

You wouldn't be able to call $(document).ready in the first place if the above wasn't the case.

重要的是要了解,在幕后您将直接的常规事件侦听器附加到document.选择器实际上所做的就是,如果在事件传播路径中没有与选择器匹配的元素,则不调用处理程序回调.而且很显然,如果传播被低级别的侦听器过早停止,则在这种情况下也不会触发.

It's important to understand that behind the scenes you are attaching a direct, normal event listener to document. All the selector practically does is that your handler callback is not called if no elements matched your selector in the event propagation path. And obviously if propagation is stopped prematurely by lower level listeners, it wouldn't be fired in that case either.

这篇关于功能和文档准备好的jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆