如何使用jQuery获取,操作和替换文本节点?

这是我的代码:

  • Printing from $10
  • 我在任何给定的页面上都有大约15个这样的块,我想取文本节点(从$ X开始),使用正则表达式选择X并将其设置为数值变量,然后将其乘以%,并且将其附加到原始节点。 例如,如果原始节点说“从10美元起”,我想用“从10美元到2.60美元”替换它。 我可以在单个节点上使用replace()和正则表达式来做到这一点,但是我无法使用jQuery迭代所有这些。 我可以将这样的转换应用于jQuery对象,还是我需要以某种方式转换它然后使用标准的Javascript函数?

    谢谢!

    以下是如何选择文本节点。

    这是(你的骨架)一旦你拥有它们你会做什么:

     $('li.det_price').contents().filter(function() { return this.nodeType == 3; }).text(function (i, text) { return text.replace(/* your schtuff here */); }); 

    显然jQuery不能很好地与文本节点一起播放

    是时候得到(一点点)hacky:

     var rnotwhite = /\S/; // to omit text nodes that are solely white space // tweak this as needed $('li.det_price').contents().filter(function() { return this.nodeType === 3 && rnotwhite.test($(this).text()); }).text(function (i, text) { this.replaceWholeText(text + ' replaced'); // or, for more cross-browser-ness // this.nodeValue = text + ' replaced'; }); 

    -->查看这个甜蜜的演示<--

    --> IE兼容演示<--

    现在就是这样的交易:如果你能控制标记,那么最好的解决方案就是在包装你真正感兴趣的文本节点,如下所示:

     
  • Printing from $10
  • 然后你可以这样做( 方式少草图,IMO):

     $('li.det_price > a + span').text(function (i, text) { return text + ' replaced'; }); 

    -->更多演示优点<--

    您需要使用每个function:

     $("li.det_price a").each(function(index, Element){ //Element holds the current anchor, manipulate it's contents at will $("Element").val("some new value..."); }) 

    $("li.det_price a").text()将为您提供该LI的文本(不幸的是,具有该类引用的所有LI节点)。 要获得该特定LI的文本,您必须为其提供ID,或者找到其他方法来唯一地标识它。

    一旦你确定它唯一,你可以简单地在.text()括号中放一个字符串来改变你拥有的。 例如,

    $("li.det_price a").text('Not Printing')会将您的文字从’Printing’更改为’Not Printing’。