2013-05-14 91 views
2

我试图用jQuery在<span>标签中换行标签。下面的代码不起作用。请指出我出错的地方。也请建议一个更好的/不同的方法。在html标签中换行文本

var mysearch = '(05/13/2012-11/13/2012)'; 
$('table:eq(0) tr:eq(1) th:contains("' + mysearch + '")').filter(function() { 
    return this.html().replace('(05/13/2012-11/13/2012)', '<span class = "red"> (05/13/2012-11/13/2012)</span>'); 
}); 

Demo on jsFiddle

+0

你可以让你的问题的小提琴 – 2013-05-14 17:56:27

回答

1

试试这个 -

$('table:eq(0) th:contains("' + mysearch + '")').contents().wrapAll('<span class = "red"></span>'); 

工作演示-->http://jsfiddle.net/8kMqW/2/

+0

感谢ü。但是,即使在应用了ur代码之后,我也没有看到文本被span包裹。 – BumbleBee 2013-05-14 18:06:28

+0

谢谢你。我只想将“mysearch”的文本包装在中,而不是整个文本。 – BumbleBee 2013-05-14 19:20:38

5

在你的代码this的是,没有html方法的DOM元素的对象,还你不不需要filter方法,可以使用html HOD。

$('table:eq(0) tr:eq(1) th:contains("' + mysearch + '")').html(function(_, html) { 
    return html.replace('(05/13/2012-11/13/2012)', '<span class="red"> (05/13/2012-11/13/2012)</span>'); 
}); 

如果th的含量等于mysearch字符串,你也可以使用wrapInner方法:

$('table:eq(0) tr:eq(1) th').filter(function(){ 
    return $.trim($(this).text()) === mysearch; 
}).wrapInner('<span class="red"></span>'); 

JS Fiddle

+1

删除了我自己的答案,因为我没有注意到使用'filter()'代替'html()'(并且改进我的答案必然会抄袭(或者至少*重复*)自己的答案) 。加一个给你,先生! – 2013-05-14 18:01:17

+0

谢谢你。但是,即使在应用了ur代码之后,我也没有看到文本被span包裹。 – BumbleBee 2013-05-14 18:05:45

+0

@DavidThomas哦,是的,OP的代码使用'filter'方法,谢谢。 – undefined 2013-05-14 18:09:34