如何通过javascript addListener函数值来改变里面的函数

时间:2017-08-29 07:17:34

标签: javascript jquery

我有addListener功能,change功能就在那里。如何使用javascript

addListener结果传递给change函数
$(document).ready(function() {
  // find pincode
  var input = document.getElementById('location_input');
  var options = {
    types: ['address'],
    componentRestrictions: {
      country: 'in'
    }
  };
  autocomplete = new google.maps.places.Autocomplete(input, options);
  var pincode;

  google.maps.event.addListener(autocomplete, 'place_changed', function fun1() {
    var place = autocomplete.getPlace();
    for (var i = 0; i < place.address_components.length; i++) {
      for (var j = 0; j < place.address_components[i].types.length; j++) {
        if (place.address_components[i].types[j] === "postal_code") {
          pincode = place.address_components[i].long_name;
          fun2(pincode);
          //alert(pincode);
        } //return pincode;
      }
    }
  });

  $('input[type="checkbox"],#location_input').change(function fun2(val) {
    var ids = ['filter_AFFILIATION_1', 'filter_AFFILIATION_2', 'filter_AFFILIATION_3', 'filter_AFFILIATION_4'];
    var data = {};
    for (var i = 0; i < ids.length; i++) {
      if (document.getElementById(ids[i]).checked === true) {
        data['request' + i] = $('#' + ids[i]).val();
      }
    }
    var pincode = val;
    alert(pincode);
    console.log(pincode);
  });
});

这里有fun1fun2两个函数。如何将fun1 pincode值传递给fun2内部?

1 个答案:

答案 0 :(得分:0)

您已在全球范围内定义了密码。 只是使用它。 这里function fun2(val) val是传递给事件回调的Event对象。 而且你不必使用命名函数,anon funcs将作为事件回调。

$(document).ready(function () {
    // find pincode
    var input = document.getElementById('location_input');
    var options = {
        types: ['address'],
        componentRestrictions: {
            country: 'in'
        }
    };
    autocomplete = new google.maps.places.Autocomplete(input, options);
    var pincode;
    google.maps.event.addListener(autocomplete, 'place_changed', function () {
        var place = autocomplete.getPlace();
        for (var i = 0; i < place.address_components.length; i++) {
            for (var j = 0; j < place.address_components[i].types.length; j++) {
                if (place.address_components[i].types[j] === "postal_code") {
                    pincode = place.address_components[i].long_name;
                } //return pincode;
            }
        }
    });
    $('input[type="checkbox"]').change(function (event) {
        var ids = ['filter_AFFILIATION_1', 'filter_AFFILIATION_2', 'filter_AFFILIATION_3', 'filter_AFFILIATION_4'];
        var data = {};
        for (var i = 0; i < ids.length; i++) {
            if (document.getElementById(ids[i]).checked === true) {
                data['request' + i] = $('#' + ids[i]).val();
            }
        }
        alert(pincode);
        console.log(pincode);
    });
});