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

标签 javascript jquery string

这是我的代码:

<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/

相关文章:

javascript - 如何克隆元素并生成动态 ID

javascript - 使用带有 SqlDependency 的 SignalR 推送数据库更新

javascript - jQuery 按索引不一致的值过滤对象

javascript - 如何在基于 JSON 结构的复选框中显示内部子 bool 值?

Firefox 7.0.1 上的 Jquery 动画滞后

javascript - 简单的 JS insideHTML 问题 - 包含 var 中保存的图像 src

c++将大文本文件读取为字符串(大于string::max_size)

javascript - 使用 jQuery 检测表单文件中的更改

ios - 如何复制两个标签的结果?

python - 从日期列中获取月份