本文介绍了有什么区别:$(this.el).html 和 this.$el.html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别:

$(this.el).html

this.$el.html

阅读一些骨干例子,有些是用一种方式来做的,另一些则是另一种方式.

Reading a few backbone examples and some do it one way and other another way.

推荐答案

$(this.el) 使用 jQuery(或 Zepto)包装元素.因此,如果您的视图 HTML 是这样的:

$(this.el) wraps an element with jQuery (or Zepto). So, if your view HTML was this:

<div id="myViewElement"></div>

...and this.el 引用了那个 div,然后 $(this.el) 就相当于直接通过 jQuery 检索它: $('#myViewElement').

...and this.el referenced that div, then $(this.el) would be the equivalent of retrieving it directly via jQuery: $('#myViewElement').

this.$el 是对 jQuery(或 Zepto)对象的缓存引用,因此是调用 $(this.el) 时获得的副本.这样做的目的是让您无需调用 $(this.el),这可能会产生一些开销,从而导致性能问题.

this.$el is a cached reference to the jQuery (or Zepto) object, so a copy of what you would get from calling $(this.el). The intent is to save you the need to call $(this.el), which may have some overhead and therefor performance concerns.

请注意:两者并不等效.this.el 单独是对宿主对象 HTMLElement 的引用——不涉及库.这是document.getElementById 的返回.$(this.el) 创建 jQuery/Zepto 对象的新实例.this.$el 引用前一个对象的单个实例.只要您了解多次调用 $(this.el) 的成本,使用它们中的任何一个都不是错误".

Please note: the two are NOT equivalent. this.el alone is a reference to a host object HTMLElement -- no libraries involved. This is the return of document.getElementById. $(this.el) creates a new instance of the jQuery/Zepto object. this.$el references a single instance of the former object. It is not "wrong" to use any of them, as long as you understand the costs of multiple calls to $(this.el).

在代码中:

this.ele = document.getElementById('myViewElement');
this.$ele = $('#myViewElement');

$('#myViewElement') == $(this.ele);

另外,值得一提的是 jQuery 和 Zepto 有部分内部缓存,因此对 $(this.el) 的额外调用 可能 无论如何最终都会返回缓存的结果,这就是为什么我说可能有性能问题".也可能没有.

Also, it is worth mentioning that jQuery and Zepto have partial internal caches, so extra calls to $(this.el) might end up returning a cached result anyway, and that's why I say "may have performance concerns". It also may not.

文档

  • view.$el - http://backbonejs.org/#View-$el
  • $ in backbone - http://backbonejs.org/#View-dollar
  • jQuery base object - http://api.jquery.com/jQuery/
  • Zepto base object - http://zeptojs.com/#$()

这篇关于有什么区别:$(this.el).html 和 this.$el.html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 08:34