Jquery / Javascript:用html标签替换html内容

时间:2013-11-22 17:29:57

标签: javascript jquery

我是一个jquery学习者,

我的表

<table id="table">
<tr >
    <th>column 1</th>
    <th>Address</th>
    <th>column 3</th>
</tr>
<tbody>
    <tr>
        <td>test data</td>
        <td class="address">My compnay, \n New Hil \n
            six singama \n India
        </td>
        <td>some data</td>
    </tr>
     <tr>
        <td>test data</td>
         <td class="address">New Branch, \n New Hil \n
            six singama \n India
        </td>
        <td>some data</td>
    </tr>
     <tr>
        <td>test data</td>
         <td class="address">Some company, \n New arcade \n
            six singama \n India
        </td>
        <td>some data</td>
    </tr>
   </tbody> 

每行的第二列都有一个包含\ n字符的地址,我想在加载页面时用\n标记替换<br>(当文档准备就绪时)

Jsfiddle here

 $( document ).ready(function() {
   var columns = $('tr').find('td:eq(2  )')
  });

1 个答案:

答案 0 :(得分:3)

尝试:

$(document).ready(function() {
    $("tr:gt(0)").each(function(){
        var t = $(this).find("td:eq(1)");
        var tx = $(t).text();
        tx = tx.replace(/\\n/g,'<br/>');
        $(t).html(tx);
    });
});

Fiddle here.

你也可以尝试这样:

$(document).ready(function() {
    $("td:contains(\n)").each(function(){        
        var t = $(this).text();        
        t = t.replace(/\\n/g,'<br/>');
        $(this).html(t);
    });
});

Fiddle here.