我试图将第二列的锚点更改为包含来自第一和第三列的信息的链接。
我们如何使用Jquery来做到这一点呢?
请参阅下面的例子:
我该怎么做呢?
<table>
<tr><th>Model Id</th><th>Model Num(s)</th><th>Company</th></tr>
<tr><td>1</td><td><a>Model-1</a></td><td><span>Apple</span></td></tr>
<tr><td>2</td><td><a>Model-2</a></td><td><span>MS</span></td></tr>
<tr><td>2</td><td><a>Model-3</a><a>Model-4</a><a>Model-5</a></td><td><span>IBM</span></td></tr>
</table>对此:
<table>
<tr><th>Model Id</th><th>Model Num(s)</th><th>Company</th></tr>
<tr><td>1</td><td><a href="models/model-1.html?&id=1&div=Apple">Model-1</a></td><td><span>Apple</span></td></tr>
<tr><td>2</td><td><a href="models/model-2.html?&id=2&div=MS">Model-2</a></td><td><span>MS</span></td></tr>
<tr><td>3</td><td><a href="models/model-3.html?&id=3&div=IBM">Model-3</a><a href="models/model-4.html?&id=4&div=IBM">Model-4</a><a href="models/model-5.html?&id=5&div=IBM">Model-5</a></td><td><span>IBM</span></td>
</tr>
</table>发布于 2014-07-30 15:07:56
这应该是可行的:
$('table tr td:nth-child(2) a').each(function() {
var link = $(this);
var siblings = link.parent().siblings();
var id = siblings.eq(0).text();
var div = siblings.eq(1).text();
var href = 'models/' + link.text().toLowerCase() + '.html?&id=' + id + '&div=' + div;
link.attr('href', href);
});发布于 2014-07-30 15:20:19
假设HTML的结构是一致的(第一行是标题行,列数永远不变),下面的脚本应该可以工作:
$(document).ready(function () {
// Go through each <tr> after the first one
$("table tr:gt(0)").each(function(){
currRow = $(this);
var id = currRow.find("td:nth-child(1)").text();
var div = currRow.find("td:nth-child(3)").text();
// Assemble final href for each link in current row
currRow.find("a").each(function(){
var model = $(this).text().toLowerCase();
var finalHref = "models/" + model + ".html?&id=" + id + "&div=" + div;
$(this).attr("href", finalHref);
});
});
});该脚本在第一个元素之后遍历每个<tr>元素,并根据该<tr>的内容设置它查找的每个子锚标记的href。这是一个JSFiddle演示。
希望这能有所帮助!如果你有任何问题,请告诉我。
https://stackoverflow.com/questions/25039902
复制相似问题