使用jQuery,如何修改标签之外的文本? [英] Using jQuery, how to modify text outside of tags?

查看:96
本文介绍了使用jQuery,如何修改标签之外的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个文本字符串,它们都与一个跨度和一个div的内部相邻,有什么方法可以修改该文本,从而使周围的HTML保持不变?例如:

 < 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆