我有一个基于 tinymce 的文档,我需要对其进行查找/替换。
文档中的标记将具有特定的 <!--nextpage-->
html 中的评论标签如下:
<p>some content</p><!--nextpage-->
<p>some more content</p><!--nextpage-->
我需要执行一个脚本查找/替换来遍历每次出现的 <!--nextpage-->
在标记中并将其替换为 anchor 元素。
anchor 需要有一个连续的id值“anchor+N”,其中N
是anchor在文档中的索引加1。
因此,对于上面的文本,替换将产生:
<p>some content</p><a id="anchor1"></a>
<p>some more content</p><a id="anchor2"></a>
jQuery 可以做到这一点还是我需要使用其他东西,比如正则表达式?
最佳答案
你可以得到 innerHTML
的 body
并对其进行替换,完成后写回新文本。
DEMO - 1 - 使用 JavaScript 替换 HTML
虽然代码有效,但替换 HTML 可能会产生后果。如果您有任何事件绑定(bind)到 body
中的任何元素由于您已替换 HTML,它们现在将解除绑定(bind)。
如果可能的话,如果你对它有任何影响,我不会使用 <!--nextpage-->
作为占位符,但可能是一个空元素,您可以使用选择器定位,可能类似于 <div class="nextpage-placeholder"></div>
例如。
这样您就可以仅定位和替换特定元素,而不会影响其余代码。
DEMO - 2 - 使用 jQuery 替换元素
另一种方法可能只是将类分配给实际的 p
标记并简单地使用 jQuery after
添加 anchor 。
DEMO - 3 - 使用 jQuery 添加新 anchor
来自 DEMO 的代码以防 fiddle 死机
演示 - 1
<p>some content</p><!--nextpage-->
<p>some more content</p><!--nextpage-->
var text = document.body.innerHTML;
var targetText = "<!--nextpage-->";
var index = 1;
while(text.indexOf(targetText) > -1){
text = text.replace(targetText, '<a id="anchor' + index + '"></a>');
index++;
}
document.body.innerHTML = text;
演示 - 2
<p>some content</p><div class="nextpage-placeholder"></div>
<p>some more content</p><div class="nextpage-placeholder"></div>
var $elements = $(".nextpage-placeholder");
$elements.each(function(index){
$(this).replaceWith('<a id="anchor' + (index+1) + '"></a>')
});
演示 - 3
<p class="nextpage-placeholder">some content</p>
<p class="nextpage-placeholder">some more content</p>
var $elements = $(".nextpage-placeholder");
$elements.each(function(index){
$(this).after('<a id="anchor' + (index+1) + '"></a>')
});
关于javascript - 正则表达式或 jQuery 以迭代计数进行查找/替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14490406/