我如何调用函数并将其放入方法中

时间:2014-01-22 15:54:10

标签: javascript jquery function

我有这样的功能:

$(document).ready(function () {

    $('.SelectID').click(function (e) { 
var output;
        var select = $(this);
        switch (select.text()){
            case "FirstOption":
                var a = ("1");
                break;
            case "SecondOption":
                var b = ("2");
                break;
        }
        var output = [a|| b];
        return output;
    }
    $(document).on("click", "#Soemthinhg", function () {
    data1 = $('#something').val();
    data2 = $(output).val();

    AjaxMethod(data1, data2 )
});
});
  

问题是,当我运行代码时,它说0x800a138f - JavaScript运行时错误:无法获取未定义或空引用的属性'toLowerCase'

2 个答案:

答案 0 :(得分:1)

您可以使用闭包范围变量来执行此操作

$(document).ready(function () {
    //declare it in a closure scope so that the global scope will not get polluted
    var output;
    $('.SelectID').click(function (e) {
        var select = $(this);
        switch (select.text()) {
            case "FirstOption":
                var a = ("1");
                break;
            case "SecondOption":
                var b = ("2");
                break;
        }
        output = [a || b];
    })
    $(document).on("click", "#Soemthinhg", function () {
        data1 = $('#something').val();
        //here use the closure variable
        data2 = $(output).val();

        AjaxMethod(data1, data2)
    });
});

使用全局变量(不推荐)

//declare the variable in global scope
var output;
$(document).ready(function () {
    $('.SelectID').click(function (e) {
        var select = $(this);
        switch (select.text()) {
            case "FirstOption":
                var a = ("1");
                break;
            case "SecondOption":
                var b = ("2");
                break;
        }
        output = [a || b];
    })
});
$(document).on("click", "#Soemthinhg", function () {
    data1 = $('#something').val();
    //here use the global variable
    data2 = $(output).val();

    AjaxMethod(data1, data2)
});

答案 1 :(得分:0)

您已在document.ready函数中声明了输出变量,它在范围之外不可用。如果要访问document.ready函数之外的输出变量,请将其声明为全局变量。

您可以在任何函数

之外将其声明为var output;之类的全局变量

或在document.ready中作为window.output = [a | b]

$(document).ready(function () {
        $('.SelectID').click(function (e) { 
            var select = $(this);
            switch (select.text()){
                case "FirstOption":
                    var a = ("1");
                    break;
                case "SecondOption":
                    var b = ("2");
                    break;
            }
            window.output = [a|| b];
            return output;
        }
        });

    $(document).on("click", "#Soemthinhg", function () {
        data1 = $('#something').val();
        data2 = $(output).val();

        AjaxMethod(data1, data2 )
    });