2016-06-13 19 views
1

私はこのようなテーブルを持っている:Javascriptリファクタリング - どのように?

<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要素からのリンクを作成します。しかし、私のテーブル上の他の部分では、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私はより多くのコードを持っています。

答えて

3

このような機能で多くの繰り返しを保存できます。

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

関連する問題