Javascript 重构 - 怎么做?

标签 javascript refactoring

我有这样的表:

<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)');

JSFiddle

关于Javascript 重构 - 怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37790406/

相关文章:

python - 将状态传递给函数与调用类实例上的方法

android-studio - 如何在 Android Studio 中禁用/通过重构预览窗口

javascript - jQuery:保存两个可排序div内的div的位置

javascript - Google-App-Script base64 与 javascript base64 解码

php - 创建一个按钮以允许用户将页面另存为文件?

javascript - 如何让这些按钮向右浮动并垂直对齐一些垂直间距

javascript - 在 script.aculo.us 中使用 jQuery noConflict()

php - 测试调用静态方法的 PHP 代码

python - Python 中 R 的 seq_len 等价物

java - 可以将 Java 嵌套/匿名类转换为顶级类的命令行工具