Jquery 在更改事件中使用函数

Jquery 在更改事件中使用函数,jquery,Jquery,当选择框更改时,我想调用一个函数,但我遇到了一些范围问题: $(document).ready(function () { function showHint(val) { if (TypeVal == 'ordertotal') { $('.text-hint').html('Use format MIN_PRICE|MAX_PRICE:AMOUNT'); } else if (TypeVal == 'totalitems') {

当选择框更改时,我想调用一个函数,但我遇到了一些范围问题:

$(document).ready(function () {
    function showHint(val) {
        if (TypeVal == 'ordertotal') {
            $('.text-hint').html('Use format MIN_PRICE|MAX_PRICE:AMOUNT');
        } else if (TypeVal == 'totalitems') {
            $('.text-hint').html('Use format MIN_ITEMS|MAX_ITEMS:AMOUNT');
        } else {
            $('.text-hint').html('Enter the shipping cost');
        }
    }
    var TypeVal = $('#Type').val();
    showHint(TypeVal);
    $('#Type').on('change', function () {
        var TypeVal = $(this).val();
        showHint(TypeVal);
    });
});

如何使showHint函数能够在更改函数期间使用?

您已经通过showHint函数内的val传递了所需的值

function showHint(val) {
    // no need to use TypeVal here as you are passing the value via the function param 'val'
    // keep in mind that 'val' will be the value attribute of the option tag in the select field
    if (val == 'ordertotal') {
        $('.text-hint').html('Use format MIN_PRICE|MAX_PRICE:AMOUNT');
    } else if (val == 'totalitems') {
        $('.text-hint').html('Use format MIN_ITEMS|MAX_ITEMS:AMOUNT');
    } else {
        $('.text-hint').html('Enter the shipping cost');
    }
}

showHint($('#Type').val());
$('#Type').on('change', function () {
    showHint($(this).val());
});
您可以继续使用TypeVal,但在您的更改处理程序中,您将值设置为范围为更改处理程序的TypeVal,而不是全局范围。如果您想继续使用TypeVal变量,那么只需删除变更处理程序中的var声明。这将使用全局TypeVal变量

var TypeVal = $('#Type').val(); // this is scoped to the $(document).ready(function() {}
showHint(TypeVal);
$('#Type').on('change', function () {
    // var TypeVal = $(this).val(); // this is scoped to the change function
    TypeVal = $(this).val(); // this is the same var in the document ready scope
    showHint(TypeVal);
});

演示位于

将showHint的声明移到文档之外。准备上述操作应该可以。您遇到了哪些范围问题?你犯了什么错误?发生了什么或没有发生什么?