【问题标题】:Replace Text but not inside url替换文本但不在 url 内
【发布时间】:2014-03-22 20:56:14
【问题描述】:

我必须遵循以下结构:

<div class='xx'>
  That is awesome!!
<a href="http://www.his-stuff.com">yodel</a>
</div>

<div class='xx'>
   can't touch this
</div>

现在我想替换所有出现的“is”,无论它们是否单独存在。 我是这样做的:

$('.xx').each(function()
{
   $(this).html($(this).html().replace("is","was"));
});

我想要以下结果:

太棒了 -> 太棒了

不能碰这个 -> 不能碰这个

这样可以,但是包含“is”的url也被修改了

www.hwas-stuff.com

我不想替换 url 但所有其他的 url

信息:我不能使用 text() 代替 html() 因为“真实”代码有点复杂(插入图像而不是文本)

【问题讨论】:

标签: jquery dom


【解决方案1】:

试试这个:

$('.xx').contents().filter(function() {
    return this.nodeType == Node.TEXT_NODE && this.nodeValue.trim() != '';
}).each(function() {
    this.nodeValue = this.nodeValue.replace('is','was');
});

Working demo

来自我在 Stack Overflow 上提出的一个问题:https://stackoverflow.com/a/11167387/1420186

【讨论】:

  • 遗憾的是我不能用它来插入图像。它将显示源
  • 对不起,你刚刚把我弄丢了,我不明白你的需要了。只是不清楚。
  • 您的解决方案将我引向了正确的方向。我必须做一些那里描述的修改:stackoverflow.com/questions/7698673/…
【解决方案2】:

你可以这样做:

<div class='xx'>
    That is awesome!!
</div>
<a href="http://www.his-stuff.com">yodel</a>

或:

<div class='the-style'>
    <div class='xx'>
        That is awesome!!
    </div>
    <a href="http://www.his-stuff.com">yodel</a>
</div>

或:

<div class='foo bar'>
    <span class='is-was'>That is awesome!!</span>
    <a href="http://www.his-stuff.com">yodel</a>
</div>

我会优先修复你的 html 结构和方法,而不是试图找到一些时髦的方法来修补问题而不真正修复它。你未来的自己会更加感激你。

创建类时,请确保它们执行非常具体(封装)的工作,并使名称具有描述性,如果您查看 twitter 引导库,这是一个了不起的示例。

【讨论】:

  • 抱歉没有提到:我不能修改html,只能修改脚本
  • 那么我会接受 TrungDQ 的提议。据我所见和理解,它可以满足您的需求。
猜你喜欢
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
  • 2017-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多