1

我有一个jquery在右键单击事件上显示菜单的功能。我希望从函数内部的父函数访问一个对象callback

我正在使用以下JQuery 插件来获取上下文菜单。

这是代码:

function OnContextMenu() {

     //alert(key + ' ' +this.Node.Content);
     var localNode = this.Node;
     alert(localNode.Content); //CORRECT NODE VALUE GETS ALERTED

        $.contextMenu({
            selector: '.Container', 
            callback: function(key, options) {
                var m = "clicked: " + key;
                 alert(localNode.Content); //ALWAYS PRINTS THE VALUE OF THE VERY FIRST NODE THAT WAS CLICKED. 
                // window.console && console.log(m) || alert(m); 
            },
            items: {
                "edit": {name: "Edit", icon: "edit"},
                "cut": {name: "Cut", icon: "cut"},
                "copy": {name: "Copy", icon: "copy"},
                "paste": {name: "Paste", icon: "paste"},
                "delete": {name: "Delete", icon: "delete"},
                "sep1": "---------",
                "quit": {name: "Quit", icon: "quit"}
            }
        });
    }

如您所见,我将值存储在变量中:

var localNode = this.Node;

callback并在函数内使用这个变量。特殊之处在于,alert(localNode.Content);第一次单击菜单时,回调内部会给出正确的值。之后,即使alert外部函数的 正确地给出了不同的值,内部回调函数仍然显示与第一次相同的旧值。

4

2 回答 2

0

我不知道该.contextMenu()方法(也许您可以将我们指向一个 URL),但似乎上下文菜单只添加了一次(!),.Container并且对于每个后续调用它只会返回(因为上下文菜单已经存在.Container)。这只是一个有根据的猜测。

于 2012-09-28T06:00:36.497 回答
0

现在感觉很愚蠢,因为我在这里错过了一件非常简单的事情。我可以通过在函数外部声明变量来解决这个问题,就像使用全局变量一样。

下面是变化:

 var localNode;

 function OnContextMenu() {

 //alert(key + ' ' +this.Node.Content);
 localNode = this.Node;
 alert(localNode.Content); //CORRECT NODE VALUE GETS ALERTED

    $.contextMenu({
        selector: '.Container', 
        callback: function(key, options) {
            var m = "clicked: " + key;
             alert(localNode.Content); //ALWAYS PRINTS THE VALUE OF THE VERY FIRST NODE THAT WAS CLICKED. 
            // window.console && console.log(m) || alert(m); 
        },
        items: {
            "edit": {name: "Edit", icon: "edit"},
            "cut": {name: "Cut", icon: "cut"},
            "copy": {name: "Copy", icon: "copy"},
            "paste": {name: "Paste", icon: "paste"},
            "delete": {name: "Delete", icon: "delete"},
            "sep1": "---------",
            "quit": {name: "Quit", icon: "quit"}
        }
    });
}
于 2012-09-28T11:14:49.117 回答