简体   繁体   English

将变量从一个JavaScript回调匿名函数传递给另一个

[英]Pass variable from one JavaScript callback anonymous function to another

As shown below, I am passing a variable from the inputclass callback to the validate callback. 如下所示,我正在将一个变量从inputclass回调传递给validate回调。

Could it be done so without using a global variable so it will be local to the instance when applying the jQuery plugin to the given element? 是否可以在不使用全局变量的情况下做到这一点,以便在将jQuery插件应用于给定元素时在实例中是局部的?

$('#name').editable({
    inputclass: function() {
        globalVariable=this;
    },
    validate: function (value) {
        console.log(globalVariable);
        return 'pause';
    }
});

Fiddle 小提琴

Since this in inputclass() and validate() are referring to different elements, it's a bit troublesome to share data. 由于inputclass()和validate()中的这个是指不同的元素,因此共享数据有点麻烦。 My idea is also using data(), but to pass data from inputclass() to validate(), you will need to travel up the dom from input that inputclass() refer to, up to .ui-tooltip, look for the element that validate() is referring to through id 我的想法也使用data(),但是要将数据从inputclass()传递到validate(),您将需要从inputclass()所指输入的dom向上移动,直到.ui-tooltip,寻找元素validate()通过id引用

$('#name').editable({
    inputclass: function(e, f) {
        $("a[aria-describedby=" + $(this).closest(".ui-tooltip").prop("id") + "]").data("shared", "somedata");
    },
    validate: function (value) {
        console.log("validate", $(this).data("shared"));
        return 'pause';
    }
});

Updated jsfiddle to demonstrate: 更新了jsfiddle来演示:

jsfiddle 的jsfiddle

I would recommend using data attributes here to pass data. 我建议在这里使用数据属性来传递数据。

$('#name').editable({
    inputclass: function() {
        var value = 'some value';
        $(this).data('input-value', value);
    },
    validate: function (value) {
        var inputValue = $(this).data('input-value');
        console.log(inputValue);
        return 'pause';
    }
});

This method will work only if you know the inputClass function gets called before validate 仅当您知道在validate之前调用了inputClass函数时,此方法才validate

PS: If you just want to pass this , there is absolutely no need for that, since it will be bind automatically in both functions. PS:如果只想传递this ,则绝对不需要,因为它将在两个函数中自动绑定。

You need to define that variable outside the scope of functions: Try this: 您需要在函数范围之外定义该变量:尝试以下操作:

  var globalVariable;
    $('#name').editable({
        inputclass: function() {
            globalVariable='your value';
        },
        validate: function (value) {
            console.log(globalVariable);
            return 'pause';
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM