2015-07-20 76 views
0

我有一个功能,我想,当一个选择框改为打电话,但我有一些范围问题:使用改变事件中的功能

$(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功能,能够在更换功能期间使用?

+2

移动的'showHint()''中的document.ready()' – dave

+1

以上应该工作之外的声明... – tymeJV

+0

什么 “范围的问题” 你有?你得到什么错误?发生了什么或没有发生? – j08691

回答

-1

您已通过您通过val需要showHint函数内部的值

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,但你的change处理程序中你将该值设置为一个TypeVal范围限定于改变处理程序,而不是全局范围。如果您想继续使用TypeVal var,则只需在更改处理程序中删除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); 
}); 

演示在http://jsfiddle.net/nzy8bgk5/

+0

小心解释downvote? – Juank