jquery on function and document ready

China☆狼群 提交于 2020-01-05 09:14:59

问题


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>

Should I insert the javascript code in the following block?

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

If yes, why?


回答1:


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.

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

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.




回答2:


In this case, you don't need to. Since the <script> tag is after the HTML for the elements, your code will be executed after the elements have been loaded, removing the need to use a DOM ready event handler to ensure that they have been loaded.

That said, I usually prefer to include all my JavaScript code that works with elements on the page in a DOM ready event handler even when it's not strictly necessary; that way if I decide to move it elsewhere - such as the top of the page or to an external file - or change it in some other way it's not going to break.



来源:https://stackoverflow.com/questions/11798179/jquery-on-function-and-document-ready

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!