简体   繁体   English

在html标签内换行

[英]Wrap text inside html tag

I am trying to wrap text in inside <span> tag using jQuery. 我正在尝试使用jQuery将文本包装在<span>标记内。 The below code is not working. 以下代码无法正常工作。 Please point out where I am going wrong. 请指出我要去哪里了。 Also please suggest a better/different approach. 另外,请提出更好/不同的方法。

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 jsFiddle上的演示

this in your code is a DOM Element object that doesn't have html method, also you don't need the filter method, you can use html method. this在您的代码中是没有html方法的DOM Element对象,也不需要filter方法,可以使用html方法。

$('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>');
});

If the content of the th is equal to mysearch string, you can also use wrapInner method: 如果th的内容等于mysearch字符串,则还可以使用wrapInner方法:

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

JS Fiddle JS小提琴

Try this - 尝试这个 -

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM