2015-07-20 78 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