gpt4 book ai didi

javascript - 仅替换目标 ID 中的字符串

转载 作者:行者123 更新时间:2023-11-28 11:05:51 25 4
gpt4 key购买 nike

我想替换下面示例中的[空格]-[空格]部分

This - is - an - example - message 

(包括减号前后的空格)

<div class="withthiscss">xx</div>

HTML 是:

<p class="product-title" id="fixthistitle">This - is - an - example - message</p>

我只想更改包含“fixthistitle”的 ID。

所以最终结果是:

<p class="product-title" id="fixthistitle">This<div class="withthiscss">xx</div>is<div class="withthiscss">xx</div>an<div class="withthiscss">xx</div>example<div class="withthiscss">xx</div>message</p>

通常情况下,人们只需简单地更改其中的 HTML 即可获得所需的格式,但这是预先生成的文本,因此我无法更改它。因此我需要一个 JS/jQuery 解决方案吗?

也许有人可以分享如何实现这一目标?我希望这对某人有意义。

编辑:

抱歉,ID 应该始终是唯一的。

无论如何;非常感谢您提供的许多答案/解决方案。高度赞赏!

最佳答案

id应该是唯一的,所以使用 class相反

  1. 您可以使用 html() 用于迭代和更新内容
  2. 使用 split('-') 拆分内容 (或使用正则表达式 split(/\s+-\s+/) )
  3. 现在使用 <div class="withthiscss">xx</div> 连接数组,使用 join()

$('#fixthistitle').html(function(i, v) {
return v.split('-').join('<div class="withthiscss">xx</div>')
});
.withthiscss {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="product-title" id="fixthistitle">This - is - an - example - message</p>

使用正则表达式

$('#fixthistitle').html(function(i, v) {
return v.split(/\s+-\s+/).join('<div class="withthiscss">xx</div>')
});
.withthiscss {
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="product-title" id="fixthistitle">This - is - an - example - message</p>

关于javascript - 仅替换目标 ID 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33121599/

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