javascript – 如何找出保存数据对象的元素

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

$("#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)
});

Example

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

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