Multiple events for one jQuery function
I'm changing the center point on a google map by either two dropdown fields, or a search textbox and button. For each of these events I need to geocode the input and recenter the map. I tried to put all three events into one function so I can reuse the code, but I can't get it to work. When I click on the dropdown, it tries to geocode. Any idea how I can split this up?
Code:
jQuery('#input_13, #input_6_34, #map_change_button').bind('change click',
function() {
var geocoder = new GClientGeocoder();
var address;
if ( !jQuery("#map_search").val() ) {
address = jQuery("#input_13 option:selected").text() + ", " +
jQuery("#input_6_34 option:selected").text();
}
else {
address = jQuery("#map_search").val();
}
if ( geocoder ) {
geocoder.getLatLng(
address,
function(point) {
if ( !point ) {
alert(address + " not found");
} else开发者_开发问答 {
map.setCenter(point);
marker.setPoint(point);
marker.show();
map.setZoom(13);
//jQuery("input#wp_geo_latitude").val(point.lat());
//jQuery("input#wp_geo_longitude").val(point.lng());
}
}
);
}
return false;
});
put class in every dropdownlist
say for example on your html
<select id="input_13" class="myDropDownClass"/>
<option name="box1" value="Value1">Display Text1</option>
<option name="box2" value="Value2">Display Text2</option>
<option name="box3" value="Value3">Display Text3</option>
</select>
<select id="input_6_34" class="myDropDownClass">
<option name="box1" value="Value1">Display Text1</option>
<option name="box2" value="Value2">Display Text2</option>
<option name="box3" value="Value3">Display Text3</option>
</select>
<input id="map_change_button" type="submit"/>
then on your jquery do this
// Create a function function ChangeMap() { var geocoder = new GClientGeocoder(); var address; if ( !jQuery("#map_search").val() ) { address = jQuery("#input_13 option:selected").text() + ", " + jQuery("#input_6_34 option:selected").text(); } else { address = jQuery("#map_search").val(); } if ( geocoder ) { geocoder.getLatLng( address, function(point) { if ( !point ) { alert(address + " not found"); } else { map.setCenter(point); marker.setPoint(point); marker.show(); map.setZoom(13); //jQuery("input#wp_geo_latitude").val(point.lat()); //jQuery("input#wp_geo_longitude").val(point.lng()); } } ); } return false; } // call the function ChangeMap() on the change event of the dropdown $('.myDropDownClass').change(function{ ChangeMap(); }); // call the function ChangeMap() on the click event of the submit button $('#map_change_button').click(function{ ChangeMap(); });
Why don't you put the body in a separate function and then call that function when those events are raised separately? Or maybe I misunderstood what you were asking.
精彩评论