我有下表&根据表中的文本,使表<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.com
或https://facebook.com
。
发布于 2018-12-20 10:12:24
首先,请注意HTML是无效的;您缺少</a>
标记来关闭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>
发布于 2018-12-20 10:19:49
在不使用jQuery
的情况下,只需几行代码就可以实现这一目标:
document.addEventListener("DOMContentLoaded", () => {
for (const element of document.querySelectorAll("a[href='#']")) {
element.href = element.innerText;
}
});
https://stackoverflow.com/questions/53866482
复制相似问题