为什么这个脚本不起作用?

时间:2015-12-22 作者:LukeJonGibson

我这里有剧本http://www.mikedoesweb.com/2012/convert-tag-to-google-maps-embed-automatically-with-jquery/

我需要在帖子内容中用谷歌地图替换地址。我发现的谷歌地图插件没有一个能像我需要的那样工作。

$(document).ready(function(){
  $("address").each(function(){                         
    var embed ="<iframe width=\'100%\' height=\'350\' frameborder=\'0\' scrolling=\'no\'  marginheight=\'0\' marginwidth=\'0\'   src=\'https://maps.google.com/maps?&amp;q="+ encodeURIComponent( $(this).text() ) +"&amp;output=embed\'></iframe>";
                                $(this).html(embed);

   });
});
页面上的地址嵌入如下:

<address>30 Rockafeller plaza, New York NY</address>
我在函数中放置了以下内容。php

function googleaddress_function() {
wp_enqueue_script( \'googleaddress\', get_template_directory_uri() . \'-child-theme/google-maps-address.js\', array(), null, true);
}
add_action(\'wp_enqueue_scripts\',\'googleaddress_function\');
我在页脚和页眉都试过了。

我甚至尝试将其直接嵌入到页面上,只是为了更好地衡量,我已经停用了所有其他插件以检查冲突。什么都没用?

有什么想法吗?

或者,如果您知道一个插件可以嵌入到页面上,并且可以在页面上的短代码内更改地址/元数据,而不必手动创建单独的映射,那么我将尝试这样做。

i.e. [googlemapshortcode="101 this is my address, TN56 7YT" width="100%" height="350px"]

1 个回复
SO网友:Kieran McClung

我认为谷歌地图API加载不正确是一个问题。您需要确保jQuery和Google maps API都已加载。

https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.jshttp://maps.google.com/maps/api/js

它可以是jQuery的任何最新版本,也可以来自任何来源。

假设jQuery函数包含在google maps地址中。jQuery完成加载后,下面的js文件将加载该文件。

function googleaddress_function() {
    wp_enqueue_script( \'google-maps-api\', \'http://maps.google.com/maps/api/js\' ); //Add this line
    wp_enqueue_script( \'googleaddress\', get_template_directory_uri() . \'-child-theme/google-maps-address.js\', array( \'jquery\' ), null, true); //Add jquery dependency
}
add_action(\'wp_enqueue_scripts\',\'googleaddress_function\');
然后,您可以将jQuery函数设置为无冲突模式(见下文)

jQuery(document).ready(function($) {
    $("address").each(function(){                         
        var embed ="<iframe width=\'100%\' height=\'350\' frameborder=\'0\' scrolling=\'no\' marginheight=\'0\' marginwidth=\'0\' src=\'https://maps.google.com/maps?&amp;q="+ encodeURIComponent( $(this).text() ) +"&amp;output=embed\'></iframe>";
        $(this).html(embed);
    });
});
简而言之,这是一个交换第一个$ 具有jQuery 然后添加$ 到函数后面的括号。

希望这能解决你的问题,我也附上了一个例子。

http://codepen.io/raptorkraine/pen/JGKBvx