为什么我不能在回调中引用jQuery对象
Why can I not reference my jQuery object inside a callback?
我存储了一个jquery对象(html元素的集合),但是当我在另一个函数中引用该对象时,它会返回为"未定义"!下面是我的代码:
this.container = $('#slide-menu'), // The menu container (e.g. a UL)
this.items = this.container.find('.menu-item'); // The menu items (e.g. all li's)
this.links = this.items.find('.link'); // The menu links
this.getCurrent(); // Set the current menu-item
this.getPrev(); // Set the previous menu-item
this.getNext(); // Set the next menu-item
console.log(this.items); // !!! The items exist here !!!
// Setup the menu items click events:
this.items.bind('click', function(e) {
console.log(this.items); // !!! But not here !!! ???
e.preventDefault();
o = $(e.currentTarget); // Set jquery object
if (!o.hasClass('active')) { // Prevent action on current menu-item
this.items.find('.active').removeClass('active'); // Remove the current active menu-item
o.addClass('active'); // Set new active menu item
有没有人知道为什么会发生这种情况,因为它让我发疯,在我看来这应该是不可能的。是javascript坏了吗?嗯,你觉得怎么样?
什么时候一个jquery对象不是对象?
。
当它是未定义的!
或者当它不在你想的地方。
有人知道为什么会这样吗?因为它在开车我疯了,在我看来这是不可能的。是Javascript坏了?!嗯,你觉得怎么样?
不,Javascript没有"坏"。
您假设this.items
总是指相同的东西。但事实并非如此。在你的bind
中,this
是被点击的东西,而不是它在回调函数之外的任何东西。
在你的回调中,你应该写$('#slide-menu').find('menu-item')
而不是this.items
。
这是一个范围问题。
点击事件处理程序外的this
与处理程序内的this
不同。在处理程序中,它指的是被单击的元素。外部可能是全局窗口对象。
这应该可以正常工作:
var items = this.container.find('.menu-item');
items.bind('click', function(e) {
console.log(items);
不要在JavaScript中使用this
,除非你真的需要。
相关文章:
- 传递引用 jQuery 后无法访问元素属性
- 正确引用JQuery
- 如何从我的HTML/JavaScript应用程序中引用jQuery
- 如何从aspx页面引用jquery函数
- 未定义的引用-jQuery选择器与JavaScript变量
- 引用 jQuery UI 不起作用
- 为什么我无法编译引用 jquery.d.ts 的文件
- 如何动态引用 jQuery 插件实例
- 从代码隐藏引用 jquery 库
- 引用jquery中Init函数中的设置对象
- 如何在其内部引用jQuery对象'的方法调用
- 我如何在ruby中使用cgi方法引用jquery库
- 为什么我不能在回调中引用jQuery对象
- 在外部js文件中引用jQuery事件处理程序
- 在c#代码中引用jquery变量(ASP.净MVC)
- 动态引用JQUERY中的子元素
- 是否可以引用jQuery UI对话框z索引计数器
- 在HTTPS安全页面上引用jQuery CDN
- 为什么我应该在自包含函数中引用 jQuery
- 我如何使用TypeScript和DefinitelyTyped引用jQuery选择器