Splitting text and wrapping each of the words in e

2019-08-27 19:39发布

PS: Updated Fiddle

Here's a fiddle that wraps text in elements

Here's a fiddle trying to split text using commas as delimiters and wrap each of the words in <span class="new"/>. Would anyone please tell me why it gives me Uncaught TypeError: undefined is not a function in the foreach loop?

I want the output to be

 <td>
     <span class='new'>Text</span>
     <span class='new'>that</span>
     <span class='new'>needs</span>
     <span class='new'>to</span>
     <span class='new'>be</span>
     <span class='new'>wrapped.</span>
     <span class="count">not this</span>
     <button>Wrap</button>
 </td>

Code:

$('button').click(function(){
    var wrap_it = $(this).closest('td').contents().eq(0).text();
    wrap_it = wrap_it.split(',');
    console.log(wrap_it);

    $.each(wrap_it,function(i,k){
      k.wrap('<span class="new"/>');
    })

});

HTML:

<table>
 <tbody>
   <tr>
    <td>1</td>
       <td>Text,that, needs, to, be, wrapped.<span class="count">not this</span><button>Wrap</button>
    </td>
   </tr>
   <tr>
    <td>2</td>
    <td>Text, that, needs, to, be, wrapped.<span class="count">not this</span><button>Wrap</button></td>
   </tr>
  </tbody>
</table>

2条回答
Rolldiameter
2楼-- · 2019-08-27 20:19

Also made a try

$('button').click(function () {

  var text = $(this).closest('td').contents().eq(0).text().split(','),
      len = text.length,
      result = []; 

for( var i = 0; i < len; i++ ) {
    result[i] = '<span class="new">' + text[i] + '</span>';
}
var keep = $(this).closest('td').find(".count"),
    button = $(this).closest('td').find('button');
$(this).closest('td').html(result.join(' ')).append(keep).append(button);   
});

With Fiddle: Wrap splitted text

查看更多
对你真心纯属浪费
3楼-- · 2019-08-27 20:34

I made a try:

$('button').click(function(){    
    var text = $(this).closest('td').contents().eq(0).text().split(",");
    var keep = $(this).closest('td').find(".count");
    var button = $(this).closest('td').find('button');
       for( var i = 0, len = text.length; i < len; i++ ) {
           text[i] = '<span class="new">' + text[i] + '</span>';
       }   
    $(this).closest('td').html(text.join(' ')).append(keep).append(button);  
});

fiddle

Tell me please if it suits you.

查看更多
登录 后发表回答