jQuery - 将文本转换为谷歌地图链接

时间:2016-03-16 16:20:33

标签: javascript jquery google-maps

我需要从表中获取地址并从中创建链接。我想将th元素中的文本替换为mapaLink

1)mapaLink - <a>元素应包含mapaText作为链接文字

2)href应指向谷歌地图并找到该地址

var mapa = $('th').filter(function(index) { return $(this).text() === "Address"; }).next("td"),
    mapaText = mapa.text(),
    mapaLink = $("<a />", {
    target: "_blank",
    href : "http://www.google.com/",
});

codepen在这里http://codepen.io/anon/pen/jqyPbN?editors=0010

3 个答案:

答案 0 :(得分:0)

$('th:contains("Address")').each(function() {
    var targetElem = $(this).next();
  var createStr = '<a target="_blank" href="http://www.google.com/maps/search/'+targetElem.text()+'">'+targetElem.text()+'</a>';
    $(this).next().html(createStr);
});

检查上面的代码,使用fiddle,使用contains将解决您的问题,了解有关:contains()

的更多信息

答案 1 :(得分:0)

Google地图搜索网址架构为https://www.google.com/maps/search/{your search}

所以,你用链接替换文本,你只需在每一行中找到它,然后根据模式创建一个链接就是这样。

$('th:contains(Address)').each(function(index) {
  var $this = $(this),
      mapa = $this.next(),
      mapaText = mapa.text(),
      mapaLink = $("<a />", {
        target: "_blank",
        href: 'https://www.google.com/maps/search/' + mapaText,
        text: mapaText
      });    
  
  mapa.html('').append(mapaLink);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <th>Address</th>
    <td>New York</td>
  </tr>  
  <tr>
    <th>Address</th>
    <td>Miami</td>
  </tr>  
</table>

http://output.jsbin.com/qotugi

答案 2 :(得分:0)

你可以尝试这样的事情

var mapa = $('th').filter(function(index) {
  return $(this).text() === "Address"; 
}).next("td");


$(mapa).each(function(index) {

  var mapaText = $(this).text();
  var mapaLink = $("<a />", {
    target: "_blank",
    href : "https://www.google.co.uk/maps/search/" + mapaText
  }).html(mapaText);

  $(this).html(mapaLink);
});

https://plnkr.co/edit/q2mhY5AjWBgVBB96wuF7