简体   繁体   中英

Trying to call Javascript function from innerhtml

I am trying to display a map upon clicking a button.My code is as follows.

  List.innerHTML = '<input type="button" value="Click me" onclick="'+calcRoute()+'">';

    function calcRoute() {
                var start = "san bernardino, ca";
                var end = "los angeles, ca";
                var request = {
                    origin:start,
                    destination:end,
                    travelMode: google.maps.TravelMode.DRIVING
                };
                directionsService.route(request, function(response, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        return directionsDisplay.setDirections(response);
                    }
                });
    }

calcRoute shows up as undefined while debugging. I want to display the directions between two points of interest upon clicking the button.

You're calling the calcRoute function when building the HTML:

List.innerHTML = '<input type="button" value="Click me" onclick="'+calcRoute()+'">';
// ----------------------------------------------------------------^^^^^^^^^^^

but calcRoute doesn't return anything so you're effectively saying:

List.innerHTML = '<input type="button" value="Click me" onclick="' + undefined + '">';

Perhaps you just want:

List.innerHTML = '<input type="button" value="Click me" onclick="calcRoute()">';

so that calcRoute will be called when you click on the button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM