Get undefined javascript function in IE 11

2020-04-28 11:43发布

问题:

I got some error when call function in IE 11. In my case I have two scripts inside one <script> tag.

This is my function :

<script>
function test()
{
    alert("oke");
    var currency = $('#curr_drop').val();
    var total_room_qty = calculate_amount(currency); // total all room

    var btn_class = $('#book_button').prop('class');

    var this_qty = $(this).val();
    var this_plan_type = $(this).data('plan-type');
    var this_plan_id = $(this).data('plan-id');
    var this_plan_day = $(this).data('plan-day');
}

function calculate_amount(currency = 'IDR') 
{
    //alert("ok");
    var nights = $('[name="nights"]').val();
    var total_amount = 0; var total_room_qty = 0; var total_qty_room_id = 0;

    console.log('nights: '+nights);


    return total_room_qty;
}
</script>

I call that test function from this code :

<select name="qty" class="mb10" onchange="test.bind(this)()" data-plan-type="rate" data-plan-id="38" data-plan-day="52459">
   <option value="0">0 rooms</option>
   <option value="1">1 rooms</option>
   <option value="2">2 rooms</option>
   <option value="3">3 rooms</option>
   <option value="4">4 rooms</option>
   <option value="5">5 rooms</option>
</select>

My problem is when I tried to show alert in top of function test I got undefined function test but if I close var total_room_qty = calculate_amount(currency); // total all room the alert can be shown in IE 11 browser. How it could be happen and how to I fix this ? Thanks

回答1:

The function declaration for calculate_amount is wrong. You are trying to use es6 in ie11.

function calculate_amount(currency = 'IDR') // this will work only in chrome and firefox 

Unfortunately IE didn't throw an error. That is the reason your event handler is not reachable.

change it to

function calculate_amount(currency) 
{
    currency = currency || 'IDR'; //if your intent is to set a default value for currency
    //alert("ok");
    var nights = $('[name="nights"]').val();
    var total_amount = 0; var total_room_qty = 0; var total_qty_room_id = 0;

    console.log('nights: '+nights);


    return total_room_qty;
}

example https://jsfiddle.net/karthick6891/0681reux/



回答2:

I was also having a similar error and Google brought me here.

In my case, it was also a syntax incompatibility problem with older versions of IE: the use of arrow functions (=>) is not supported.

In order to solve it, see Syntax error in IE using ES6 arrow functions.

Unfortunately, IE was telling me that the function below this expression was undefined, so it took a while to find out what was the actual error.

I hope this can save time to others with the same problem.