如何使用jQuery获取,操作和替换文本节点? [英] How can I get, manipulate and replace a text node using jQuery?

查看:102
本文介绍了如何使用jQuery获取,操作和替换文本节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的代码:

<li class="det_price">
    <a href="/designer/customize/278258?dpid=1">Printing</a> from $10 
</li>

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

I have about fifteen chunks like this on any given page, and I'd like to take the text node (from $X), select X using a regular expression and set it to a numeric variable, then multiply it by a %, and append it to the original node. For example, if the original node said "from $10" I would like to replace it with "from $10 to $2.60". I can do this using replace() and regular expressions on a single node, but I'm having trouble iterating through all of them with jQuery. Can I apply such a transformation to a jQuery object, or do I need to convert it somehow and then use standard Javascript functions?

谢谢!

推荐答案

以下是选择文本节点的方法。

这是(你的骨架)你曾经做过的事情:

Here's (the skeleton of) what you do once you've got 'em:

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






显然jQuery不能很好地发挥作用文本节点



获得(一点点)hacky的时间:


So apparently jQuery doesn't play that nicely with text nodes

Time to get (a little) 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';
});

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

--> Check out this sweet demo <--

- > 此处与IE兼容的演示< -

--> IE-compatible demo here <--

现在就是这笔交易:如果您已经控制了标记,最佳解决方案就是将文本节点包装起来实际感兴趣的是,在< span> s中,如下所示:

Now here's the deal: if you have control of the markup, the best solution for this is to wrap the text nodes you're actually interested in, in <span>s, like this:

<li class="det_price">
  <a href="/designer/customize/278258?dpid=1">Printing</a><span> from $10</span>
</li>

然后你可以这样做(方式少草图,IMO) :

and then you can just do this (way less sketch, IMO):

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

- > 更多演示善良< -

这篇关于如何使用jQuery获取,操作和替换文本节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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