如何找出包含数据对象的元素

How to find out which element hold the data object

本文关键字:元素 对象 数据 何找出 包含      更新时间:2023-09-26

如果我将数据对象传递给函数,如下所示:

$("#someobject").data({
    "prp1":"x",
    "dosomething":function(){
    callthisfunction(this);  //<---- HERE the data ref is sent to a function
   }
});
...
function callthisfunction(in_data)
{
  //how is the data element?
  var theElementHoldingTheDataIs = in_data.????;  //<--- how can I get $("#someobject")

}

我的问题是:是否有一种方法从数据通知到它依赖或属于哪个对象?

你可以使用闭包:

var obj = $("#someobject");
obj.data({
    "prp1": "x",
    "dosomething": (function(scope) {
        return function() {
            callthisfunction(scope); //<---- HERE the data ref is sent to a function
        }
    })(obj)
});

例子


或者如果你只想发送数据对象:

var obj = $("#someobject");
obj.data({
    "prp1": "x",
    "dosomething": (function(scope) {
        return function() {
            callthisfunction(scope.data());
        }
    })(obj)
});