2013-05-14 92 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