JQuery/Javascript - Search DOM for text and insert HTML(JQuery/Javascript - 在 DOM 中搜索文本并插入 HTML)
问题描述
我如何在 DOM 中搜索文档文本中的某个字符串(例如,cheese"),然后在该字符串之后立即插入一些 HTML(例如,< b >is wonderful</b >").
How do I search the DOM for a certain string in the document's text (say, "cheese") then insert some HTML immediately after that string (say, "< b >is fantastic< /b >").
我尝试了以下方法:
for (var tag in document.innerHTML) {
if (tag.matches(/cheese/) != undefined) {
document.innerHTML.append(<b>is fantastic</b>
}
}
(以上更多是我尝试过的说明,而不是实际代码.我认为语法非常错误,所以请原谅任何错误,它们不是问题).
(The above is more of an illustration of what I have tried, not the actual code. I expect the syntax is horribly wrong so please excuse any errors, they are not the problem).
干杯,
皮特
推荐答案
有一些本地方法可以在文档中查找文本:
There are native methods for finding text inside a document:
MSIE:textRange.findText()
其他:window.find()
如果发现某些内容,则操作给定的 textRange.
这些方法应该比遍历整个文档提供更多的性能.
Manipulate the given textRange if something was found.
Those methods should provide much more performance than the traversing of the whole document.
例子:
<html>
<head>
<script>
function fx(a,b)
{
if(window.find)
{
while(window.find(a))
{
var node=document.createElement('b');
node.appendChild(document.createTextNode(b));
var rng=window.getSelection().getRangeAt(0);
rng.collapse(false);
rng.insertNode(node);
}
}
else if(document.body.createTextRange)
{
var rng=document.body.createTextRange();
while(rng.findText(a))
{
rng.collapse(false);
rng.pasteHTML('<b>'+b+'</b>');
}
}
}
</script>
</head>
<body onload="fx('cheese','is wonderful')">
<p>I've made a wonderful cheesecake with some <i>cheese</i> from my <u>chees</u>e-factory!</p>
</body>
</html>
这篇关于JQuery/Javascript - 在 DOM 中搜索文本并插入 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JQuery/Javascript - 在 DOM 中搜索文本并插入 HTML


基础教程推荐
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01