【问题标题】:How do u replace a string that's not inside a specific div?你如何替换不在特定div内的字符串?
【发布时间】:2014-02-18 02:12:46
【问题描述】:

我有这个 html:

<div id="content">This following word is not <span id="notOk">ok</span> but all the other words are ok</div>

使用这个 jquery,我试图用 cool 替换单词 ok,只要单词 ok 不在跨度 #notOk 内。

var content = $('#content').html()
content = content.replace('ok', 'cool');
$('#content').html(content)

我也想保留句子,不移动任何单词,这就是我尝试时发生的情况。我想我正在寻找类似 dontGetElementByID('').?

FIDDLE

【问题讨论】:

  • 没有得到你想说的。
  • 你的意思是说如果'ok'这个词在 Id=#notOk 的范围内,你希望它被替换为'cool'?其他“好的”不应该被替换。我说的对吗?
  • 你想做什么??更改跨度内的第一个 ok,跨度外的 ok,还是两者都更改?
  • 替换后,我希望 html 为 This following word is not &lt;span id="notOk"&gt;ok&lt;/span&gt; but all the other words are cool&lt;/div&gt; 而不是 This following word is not &lt;span id="notOk"&gt;cool&lt;/span&gt; but all the other words are ok&lt;/div&gt;,这是正在发生的事情。这更清楚吗?
  • @user2891084 更改跨度外的ok

标签: javascript jquery replace


【解决方案1】:

您可以使用.contents() 方法并替换textNodes 的nodeValue 属性。

$('#content').contents().each(function(){
    if (this.nodeType === 3)
        this.nodeValue = this.nodeValue.replace('ok', 'cool');
});

http://jsfiddle.net/82tmP/

【讨论】:

【解决方案2】:

像你一样替换值..然后将其替换回来:)

var content = $('#content').html()
content = content.replace('ok', 'cool');
$('#content').html(content);

content = $('#notOk').html();
content = content.replace('cool', 'ok');
$('#notOk').html(content);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-27
    • 2012-09-04
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    相关资源
    最近更新 更多