替换td中的部分文本
我有这种格式的td
:
Business Owner - Delivery Director
me@business.com
我怎样才能用其他东西替换文本"Business Owner - Delivery Director"
?
使用this.text()获取Business Owner - Delivery Director
和me@business.com
,但我只想要Business Owner - Delivery Director.
使用.contents()
获取文本节点(使用CharacterData
接口 ),然后操作其内容:
$("td").contents()[0].data = "Businees Owner (CEO)";
在jsfiddle.net上演示
您可以使用childNodes
属性选择第一个文本节点并更改其值:
$('td')[0].childNodes[0].nodeValue = "New content";
这是一个演示: http : //jsfiddle.net/dpyNy/
使用该结构,您将必须使用split
进行字符串操作:
var td = $("selector_for_the_td_element"); var text = td.html().split("
"); text[0] = "new content"; td.html(text.join("
"));
…或使用indexOf
和substring
:
var td = $("selector_for_the_td_element"); var text = td.html(); var index = text.indexOf("
"); text = "new content" + text.substring(index); td.html(text);
现在,如果您可以将HTML结构更改为:
Business Owner - Delivery Director
me@business.com
……它变得容易多了:
$("selector_for_the_td_element > span").text("new content");
如果html结构与你发布的完全相同,你可以像这样实现:
this.childNodes[0].nodeValue = 'hello'; //this is the td element