我有这样的表:
<table>
<tr>
<th>Name</th><td>Steve Martin</td>
</tr>
<tr>
<th>Phone</th><td>XXX</td>
</tr>
<tr>
<th>Bank account</th><td>654861/46147</td>
</tr>
</table>
我对表格的相同部分使用 JavaScript。例如
$('th:contains(Name)').each(function(index) {
var $this = $(this),
dluh = $this.next(),
dluhText = dluh.text(),
dluhLink = $("<a />", {
target: "_blank",
href: 'www.google.com' + dluhText,
text: dluhText,
style: "text-decoration: none"
});
dluh.html('').append(dluhLink);
});
从 th 个元素创建链接。但是在我 table 上的其他部分,我需要从 td 元素建立链接。例如:
$('th:contains(Phone)').each(function(index) {
var $this = $(this),
dluh = $this.next(),
dluhText = dluh.text(),
dluhLink = $("<a />", {
target: "_blank",
href: 'www.google.com' + dluhText,
text: dluhText,
style: "text-decoration: none"
});
dluh.html('').append(dluhLink);
});
但大部分代码是相同的。我认为我保存了相同的代码行,但如何保存?你能帮助我吗?
关于 CODEPEN我有更多的代码。
最佳答案
使用这样的函数可以节省很多重复。
function addLink(selector) {
$(selector).each(function(index) {
var $this = $(this),
dluh = $this.next(),
dluhText = dluh.text(),
dluhLink = $("<a />", {
target: "_blank",
href: 'www.google.com' + dluhText,
text: dluhText,
style: "text-decoration: none"
});
dluh.html('').append(dluhLink);
});
}
然后像这样调用函数。
addLink('th:contains(Name)');
addLink('th:contains(Phone)');
addLink('th:contains(Bank account)');
关于Javascript 重构 - 怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37790406/