【问题标题】:JQuery make hyperlink based on Text of Anchor tagjQuery基于Anchor标签的文本制作超链接
【发布时间】:2018-12-20 10:09:28
【问题描述】:

我有下表以及根据其具有的文本制作表格单元格<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


    【解决方案1】:

    首先,请注意您的 HTML 无效;您缺少 &lt;/a&gt; 标签来关闭 table 中的锚点。

    其次,jQuery 没有getText() 方法。我假设您打算改用text()

    关于您的问题,您可以使用prop()a 元素的href 属性设置为等于它们的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>

    【讨论】:

    • 没问题,很高兴为您提供帮助
    【解决方案2】:

    您无需jQuery,只需几行代码即可实现:

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

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

    【讨论】:

      猜你喜欢
      • 2016-07-15
      • 1970-01-01
      • 2011-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-27
      • 1970-01-01
      相关资源
      最近更新 更多