gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:07:10 25 4
gpt4 key购买 nike

这是我的代码:

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

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

谢谢!

最佳答案

Here's how to select a text node.

这是(框架)一旦你得到它们你会做什么:

$('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';
});

--> Check out this sweet demo <--

--> IE-compatible demo here <--

现在是这样:如果您可以控制标记,最佳解决方案是将您真正感兴趣的文本节点包装在 <span> 中s,像这样:

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

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

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

--> More demo goodness <--

关于javascript - 如何使用 jQuery 获取、操作和替换文本节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4046482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com