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

jQuery - convert text to google maps link

本文关键字:谷歌地图 链接 转换 文本 jQuery      更新时间:2023-09-26

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

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

谷歌地图搜索网址架构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

你可以尝试这样的东西

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

$('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);
});

检查上面的代码段,使用工作小提琴,使用contains将解决您的问题,了解更多有关:contains()