如何正确通过此范围
How to pass the scope of this correctly
我在以下this
范围方面遇到问题:
var test = {
$divs: $('div'),
init: function() {
this.$divs.each(function(){
$(this).on('click', test.whatsmyid);
$(window).on("resize", test.whatsmyid);
});
},
whatsmyid: function() {
console.log($(this).attr("id"));
}
};
test.init();
http://jsfiddle.net/4NZgd/1/
单击事件正确处理this
的范围,但窗口大小调整不会。 我知道原因是this
没有传递给窗口调整大小事件,但我不想使用变量将元素传递给whatsmyid
,那么我该如何解决这个问题?
这是因为this
当被resize
调用时是窗口。Windows对象没有id
。这就是为什么它返回undefined
.
如果要更改函数内部的this
,可以使用.bind
:
$(window).on("resize", test.whatsmyid.bind(this));
小提琴 : http://jsfiddle.net/4NZgd/2/
我知道已经
接受了答案,但是并非每个浏览器都支持.bind,这意味着IE 9以下的任何内容。
所以这是一个替代答案
http://jsfiddle.net/4NZgd/9/
var test = {
$divs: $('div'),
init: function() {
this.$divs.each(function(){
var $this = $(this);
$(this).on('click', test.whatsmyid);
$(window).on("resize", function () {
test.whatsmyid.call($this);
});
});
},
whatsmyid: function() {
console.log($(this).attr("id"));
}
};
test.init();
我喜欢
将eventData传递给绑定函数。基本上,eventData 是 javascript PlainObject,您可以传递事件的信息。jQuery bind()
var varModule = {
$divs: $("div"),
init: function() {
var me = this;
me.$divs.each(function() {
$(this).bind("click", { me: $(this) }, me.findID);
$(window).bind("resize", { me: me }, me.findID);
});
},
findID: function(event) {
var me = event.data.me; //You will get PlainObject in event.data
console.log(me.attr("id")); //div object will give you id but window object wont give you id attribute
}
};
(function() {
varModule.init();
})();
相关文章:
- JavaScript 中的范围 - 正确概念化为树
- DC.js范围/焦点图表行为不正确
- 我如何在 javascript 中保持“正确”的范围,甚至是侦听器
- 更改范围时如何正确引用原始对象
- 我对以下变量范围的理解是否正确
- 如何正确设置范围输入元素的动画
- 如何正确通过此范围
- 无法在 html 中获取范围滑块的正确值
- 处理角度范围而不是$parent.$parent的正确方法
- Javascript:在数字范围之间转换,保持正确的比例
- 如何正确监视数据加载的范围
- 我可以'我没有针对我的闭包中的正确范围
- 在视图中使用compile in指令和ng repeat的组合会阻止正确更新范围元素列表
- /deep/combinator视频范围蓝色css未正确显示
- 谷歌图表+谷歌表格:指定的范围无法正确识别数据
- AngularJS中的范围隔离概念究竟是如何工作的?我的推理正确吗
- Datatable-按日期范围筛选-未返回正确的结果
- JavaScript回调&范围(引用正确的内容)
- 如何在ui.router中更改状态时正确刷新范围
- 我如何界定这个“公共”的范围?正确的方法