使用jQuery,如何修改标签之外的文本? [英] Using jQuery, how to modify text outside of tags?
问题描述
< div id =my-div>修改此文字< span id =my-span >< /跨度>< / DIV>
我尝试过类似于
$('#my-div')。html(function(i,elem){blah;});
但是这似乎导致跨度被删除并且要添加新的跨度(我注意到一些样式在跨度上丢失了。)
我知道在应用客户端代码之前最好将文本字符串包装在自己的HTML标签中,但是
这似乎起作用:
<$内容()
.filter(function(){return this.nodeType == 3;})
.replaceWith ('新文本或html');
nodeType == 3用于测试文本节点。
Given a string of text that is both adjacent to a span and inside of a div, what are some methods to modify just that text, leaving the surrounding HTML intact? For example:
<div id="my-div">modify this text<span id="my-span"></span></div>
I have tried things like
$('#my-div').html(function(i, elem){blah;});
but this seems to cause the span to be deleted and a new span to be added (I notice that some styling is lost on the span).
I realize that it would be best to wrap the text string in its own HTML tags before applying client-side code, but that is out of my control.
This seems to work:
$('#my-div').contents()
.filter(function() { return this.nodeType == 3; })
.replaceWith('new text or html');
nodeType == 3 is to test for a text node.
这篇关于使用jQuery,如何修改标签之外的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!