Jquery从数据函数获取父元素

Jquery从数据函数获取父元素,jquery,Jquery,我需要获取dataset函数的父元素,但似乎无法找到它 <div id="test"> $('#test').data('func', { me: function() { console.log(this.parent()) } }) $('#test').data('func').me(); $('#test')。数据('func'{ me:函数(){ console.log(this.parent()) } }) $('#test').data('func

我需要获取dataset函数的父元素,但似乎无法找到它

<div id="test">

$('#test').data('func', {
  me: function() {
   console.log(this.parent())
  }
})

$('#test').data('func').me();

$('#test')。数据('func'{
me:函数(){
console.log(this.parent())
}
})
$('#test').data('func').me();
我想返回的是


当然,这不起作用,但这可能吗?

是的,这是可能的。您需要将关键字
this
添加为
$(this)

$('#test')。数据('func'{
me:函数(){
console.log($(this.parent())
}
})
$('#test').data('func').me()

存储对象中的
将丢失启动jQuery对象的上下文,并指向其自身

.data()
对象的上下文中,如下所示:

{
  me: function() {
   console.log(this.parent())
  }
}
您的对象没有继承jQuery原型,因此它没有
.parent()
方法。而且没有一种干净的方法可以从
.data()
结构内部获取或提供对
$(“#test”)
的引用

您可以通过在创建
.data()
时提供对
$('#test')
的某种引用来解决这一问题—同样,也没有您想要的那么优雅

$('#test').data('func', {
  $el: $( '#test' ),
  me: function() {
   console.log( this.$el[0] );
  }
});
这将获得
元素;以依赖于在每个实例中显式引用元素为代价

$('#test')。数据('func'{
$el:$(‘测试’),
me:函数(){
console.log(这个$el[0]);
}
});
$('#test').data('func').me()

谢谢您的帮助,但这似乎并没有返回父元素?您需要将此
作为您的输出吗?