更新时间:2023-12-05 13:51:40
由于某种原因,它破坏了toggleClass函数
for some reason, it breaks the toggleClass function
当您使用.html(html)
时,它将删除该元素的所有现有html,其中包括已连接到该html的任何相应事件(例如,菜单).
When you use .html(html)
it deletes all the existing html for that element which includes any corresponding events that had been wired to that html (eg menu).
使用$(body).html(..
本质上与完全重新加载页面相同,但不调用任何JavaScript.
Using $(body).html(..
is essentially the same as completely reloading the page, but without calling any javascript.
在您的情况下,您只需要定位包含文本的节点并替换该文本即可,您可以使用以下方法进行操作:
In your case you need to target just the node that has the text and replace just that text, which you can do with:
$("*:contains(" + text + "):last")
(参考: https://***.com/a/927013/2181514 )
给予:
function replaceImg(searchString, htmlString) {
var expr = new RegExp(searchString, "gi");
$("li:contains(" + searchString + ")").html(function(i, html) {
return html.replace(expr, htmlString)
})
}
replaceImg("purple", "<img src='purple.jpg'/>")
replaceImg("red", "<img src='red.jpg'/>")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<ul>
<li>Some purple text</li>
<li>Some red text and more red text</li>
<li>second purple text</li>
</ul>
</div>