在下面的代码中,我绑定(bind)了该范围的单击事件,以便它触发 checkTOC 函数。
在该函数中,我将匹配元素的计数存储在 count 变量中。只要页面加载后内容不发生更改,这种方法就非常有效。但是,count 的值似乎不受 #content div 的页面加载后更改的影响。
如何更改代码以使计数反射(reflect) #content html 的更新值?
if(typeof jQuery!="undefined")
{
jQuery(document).ready(function($)
{
var checkTOC = function()
{
//find the count of <!--nextpage--> elements
var count = jQuery('#content').html().split("<!--nextpage-->").length - 1;
alert(count);//ALWAYS RETURNS THE INITIAL COUNT, REGARDLESS IF ACTUAL COUNT IS CHANGED AFTER PAGE LOAD VIA HTML EDITING
var pageurl = jQuery("#view-post-btn a").attr("href");
var htmlStrTOCpre = jQuery("#cb2_customTOC").text();
var htmlStrTOC = '<summary>Table of Contents</summary>\n';
htmlStrTOC += '<ol>\n';
htmlStrTOC += ' <li><a href="'+pageurl+'">Introduction</a></li>\n';
for (var i = 2; i < count+2; i++) {
htmlStrTOC += ' <li><a href="'+pageurl+i+'/">Page'+i+'</a></li>\n';
}
htmlStrTOC += '</ol>';
jQuery("#cb2_customTOC").val(htmlStrTOC);
}
jQuery("#cb-toc-click").bind("click", checkTOC);
});
}
HTML 代码
<span id="cb-toc-click">Paste Table of Contents</span>
最佳答案
您可以使用 vanilla JS 遍历 DOM,或者更确切地说,使用 #content
的子节点递归地遍历并检查它们的 element.nodeType
值(value)。如果它相当于 Node.COMMENT_NODE
(或者只是 8
如果您更喜欢魔数(Magic Number);),则意味着您正在处理评论。考虑到这一点,您可以构建任何类型的逻辑:
var commentCount = 0;
//anonymous function to be called recursively
(function(D) {
//if this is a comment, increment the counter
8===D.nodeType&&commentCount++;
//call the same function recursively for every child node
D=D.firstChild;
while (D) {
arguments.callee(D);
D=D.nextSibling;
}
})(document.getElementById('content'));//start with #content
话虽这么说,我同意这样的评论:如果您可以控制标记,就有更好的方法来处理任务。
关于jQuery 获取元素 html() 的更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14470199/