对此选择器进行原型设计
prototype this selector
如果我使用以下函数:
clusters.prototype.shop_iqns_selected_class = function() {
if(this.viewport_width < 980) {
$(this.iqns_class).each(function() {
$(this.iqn).on('click', function() {
if($(this).hasClass('selected')) {
$(this).removeClass('selected');
} else {
$(this).addClass('selected');
}
});
});
}
}
要向集群函数添加属性,我知道使用 this.viewport_width
我指的是this.viewport_width
定义的父函数,但是当我使用 jQuery 选择器 $(this)
时,我指的是$.on()
函数的父函数吗?
在 JavaScript 中,this
完全由函数的调用方式定义。 jQuery的each
函数调用你给它的迭代器函数,以设置this
到每个元素值的方式,所以在该迭代器函数中,this
不再引用它在其余代码中引用的内容。
这很容易在闭包的上下文中使用变量来解决:
clusters.prototype.shop_iqns_selected_class = function() {
var self = this; // <=== The variable
if(this.viewport_width < 980) {
$(this.iqns_class).each(function() {
// Do this *once*, you don't want to call $() repeatedly
var $elm = $(this);
// v---- using `self` to refer to the instance
$(self.iqn).on('click', function() {
// v---- using $elm
if($elm.hasClass('selected')) {
$elm.removeClass('selected');
} else {
$elm.addClass('selected');
}
});
});
}
}
在那里,我继续使用 this
来引用每个 DOM 元素,但您可以接受迭代器函数的参数,这样就不会有歧义:
clusters.prototype.shop_iqns_selected_class = function() {
var self = this; // <=== The variable
if(this.viewport_width < 980) {
// Accepting the args -----------v -----v
$(this.iqns_class).each(function(index, elm) {
// Do this *once*, you don't want to call $() repeatedly
var $elm = $(elm);
// v---- using `self` to refer to the instance
$(self.iqn).on('click', function() {
// v---- using $elm
if($elm.hasClass('selected')) {
$elm.removeClass('selected');
} else {
$elm.addClass('selected');
}
});
});
}
}
更多阅读(在我的博客中关于JavaScript this
的文章):
- 神话般的方法
- 你必须记住
this
不要在整个代码中使用this
。像$.each
这样的方法给你另一个参考:
$(".foo").each(function(index, element){
/* 'element' is better to use than 'this'
from here on out. Don't overwrite it. */
});
此外,$.on
通过事件对象提供相同的功能:
$(".foo").on("click", function(event) {
/* 'event.target' is better to use than
'this' from here on out. */
});
当你的嵌套深入时,有太多的歧义,无法使用this
。当然,你会发现另一种正在使用的方法是直接在回调中创建 that
的别名,它等于 this
:
$(".foo").on("click", function(){
var that = this;
/* You can now refer to `that` as you nest,
but be sure not to write over that var. */
});
我更喜欢在参数或事件对象中使用 jQuery 提供的值。
相关文章:
- Windows8应用程序(html&Javascript):从图片库(除了文件选择器)显示图像的另一种方式
- 在动态创建的元素上获取对特定选择器的引用
- AngularJS-在JSON选择器中使用变量名
- 每当您在选择器内移动鼠标时,悬停功能就会重复
- 使用CSS或js,使用动态选择器选择任意li的下一个元素
- jQuery最近父级的数据属性选择器
- 为什么不'在JQuery中找到第二个css选择器的工作
- 为什么 .focus() 不起作用,而 .css(“color”,“red”) 在同一个选择器上起作用
- jquery IE7中的第n个选择器
- Webdriver.io pageObject模式-通过传递参数来定义元素选择器
- jquery日期选择器年份范围默认值
- 原型中漂亮的代码,如何省略'不是函数'空结果选择器上的错误
- 带原型的第N个子选择器
- 多个带有原型的 CSS 选择器
- 对此选择器进行原型设计
- 选择器原型等库中的“这个”问题
- 在原型中使用CSS选择器触发点击事件
- 原型Js多重选择器
- 原型集属性是否适用于元素类选择器
- document.getElementsByClassName breaking jQuery 类选择器由原型覆盖引起