JQuery根据Text of Anchor标签创建超链接

问题描述 投票:1回答:2

我有下表&什么是基于它的文本使表<td>可点击/超链接的单元格的最佳方法。

<table id="fresh-table" class="table">
    <thead>
        <th data-field="id" data-sortable="true">ID</th>
        <th data-field="URL" data-sortable="true">URL</th>
        <th data-field="Results">Results</th>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td><a href="#">https://google.com</td>
            <td>Woot</td>
        </tr>     
        <tr>
            <td>1</td>
            <td><a href="#">https://facebook.com</td>
            <td>Hax</td>
        </tr>     
    </tbody>
</table>   
$(document).ready(function(){
    var x = $('.clickme').getText();
    console.log(x);
});

我想基于它得到的文本替换href的值:https://google.comhttps://facebook.com

https://codepen.io/anon/pen/zyNdrZ

javascript jquery jquery-plugins
2个回答
2
投票

首先,请注意您的HTML无效;你错过了</a>标签来关闭table内的锚点。

其次,jQuery没有getText()方法。我认为你的意思是使用text()代替。

关于你的问题,你可以使用prop()来设置href元素的a属性等于它们的text()。最简单的方法是为prop()提供一个函数,该函数将在集合中的每个元素上执行。试试这个:

$('#fresh-table a').prop('href', function() {
  return $(this).text();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="fresh-table" class="table">
  <thead>
    <th data-field="id" data-sortable="true">ID</th>
    <th data-field="URL" data-sortable="true">URL</th>
    <th data-field="Results">Results</th>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td><a href="#">https://google.com</a></td>
      <td>Woot</td>
    </tr>
    <tr>
      <td>1</td>
      <td><a href="#">https://facebook.com</a></td>
      <td>Hax</td>
    </tr>
  </tbody>
</table>

1
投票

只需几行代码就可以在没有jQuery的情况下实现这一目标:

document.addEventListener("DOMContentLoaded", () => {
  for (const element of document.querySelectorAll("a[href='#']")) {
    element.href = element.innerText;
  }
});

https://codepen.io/anon/pen/wRgqxB

© www.soinside.com 2019 - 2024. All rights reserved.