使用jQuery,如何修改标记之外的文本?
给定一个与span相邻且位于div内部的文本字符串,有哪些方法可以修改该文本,而不影响周围的HTML?例如:使用jQuery,如何修改标记之外的文本?,jquery,html,string,Jquery,Html,String,给定一个与span相邻且位于div内部的文本字符串,有哪些方法可以修改该文本,而不影响周围的HTML?例如: <div id="my-div">modify this text<span id="my-span"></span></div> 但这似乎会导致删除跨度并添加新的跨度(我注意到跨度上丢失了一些样式) 我意识到在应用客户端代码之前最好将文本字符串包装在自己的HTML标记中,但这是我无法控制的。与其修改其HTML字符串,不如修改其DOM树,
<div id="my-div">modify this text<span id="my-span"></span></div>
但这似乎会导致删除跨度并添加新的跨度(我注意到跨度上丢失了一些样式)
我意识到在应用客户端代码之前最好将文本字符串包装在自己的HTML标记中,但这是我无法控制的。与其修改其HTML字符串,不如修改其DOM树,找到顶级文本节点并处理它们。使用jQuery的
contents()
方法怎么样
您可以使用字符串替换: HTML
你有没有试过这样的方法:
$(document).ready(function(){
var elems = $('#myDiv *').detach();
$('#myDiv').text('new texts...').append(elems);
})
快的
编辑
或者按照alex的建议使用.contents()
:
这似乎有效:
$('#my-div').contents()
.filter(function() { return this.nodeType == 3; })
.replaceWith('new text or html');
nodeType==3用于测试文本节点。这是有道理的,但如何将文本作为某种对象隔离?这与我前面提到的相同。它替换文本,销毁DOM对象。当它替换文本时,如何销毁DOM对象?现在,如果我添加了
.replace(“”,)
肯定会破坏span,但在这种情况下,你是故意这么做的。同样,这会破坏span并用新的span替换它们。当我看到你的span出现在这里时,我正准备将此作为正确的解决方案来编写。美好的
$('#my-div').html(function(i,html){
return html.replace('this text', 'some new text').replace('or this text', 'and replace this text');
})
$(document).ready(function(){
var elems = $('#myDiv *').detach();
$('#myDiv').text('new texts...').append(elems);
})
$('#myDiv').contents()
.filter(function(){
return this.nodeType != 1 && $.trim($(this).text()) != '';
})
.replaceWith("I am the new text");
$('#my-div').contents()
.filter(function() { return this.nodeType == 3; })
.replaceWith('new text or html');