在特定的HTML注释后插入HTML块 [英] Insert HTML block after a specific HTML comment

查看:119
本文介绍了在特定的HTML注释后插入HTML块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在特定的HTML注释之后而不是在<div>之类的HTML元素中插入HTML代码.

I am wondering if I can insert HTML code after a specific HTML comment rather than within an HTML element such as <div>.

例如,我想在下面的第一个注释标签之后插入开始标签<div id="OUTER"><div id="INNER">;并在第二个注释标签之后添加结束标签</div></div>.有人知道该怎么做吗?

For example, I would like to insert the opening tags <div id="OUTER"><div id="INNER"> after the first comment tag below; and the closing tags </div></div> after the second comment tag. Does somebody know how to go about this?

<!-- Insert Opening Tags Below -->


<div id="CONTENT">Page Content Here</div>


<!-- Insert Closing Tags Below-->

谢谢.

Elena

推荐答案

HTML comment在DOM层次结构中具有它自己的对应Node,并且它的nodeType属性是8.诸如Firebug或Google Console之类的DOM检查器不会显示它们,但是,您可以通过查看页面的源来找到它们,如果元素是body元素的子元素,则可以通过以下方式过滤childNodes:

HTML comment has it's own corresponding Node in DOM hierarchy and it's nodeType property is 8. DOM inspectors like Firebug or Google Console do not show them, however, you can find them by viewing source of the page, if elements are children of the body element, you can filter the childNodes this way:

$('body').contents().each(function(i, elem){
    if (elem.nodeType == 8) {
       // This is a Comment node
       // Comment { data=" Insert Closing Tags Below", length=26, nodeType=8, more...}
       // You can select all the next sibilngs of the first
       // Comment node including the second Comment Node 
       // and then wrap all of them 
    }
});

做您想做的事情没有意义,浏览器仅显示服务器发送的文档的初始版本,使用JavaScript处理文档不会更改源视图.此外,除非您要操作另一个元素的innerHTML,否则您只能将Nodes添加到文档中,并且不能在DOM中放置一些字符串以将其解析为DOM元素.我建议包装#CONTENT元素:

There is no point in doing what you want, browsers only show the initial version of the document that has been sent by the server and manipulating document using JavaScript doesn't change the source view. furthermore, you can only add Nodes to the document, you can't put some strings in DOM to be parsed as a DOM element, unless you are manipulating innerHTML of another element. I would suggest wrapping the #CONTENT element:

$('#CONTENT').wrap('<div id="OUTER"><div id="INNER"></div></div>');

这将导致:

<!-- Insert Opening Tags Below -->
<div id="OUTER">
   <div id="INNER">
      <div id="CONTENT">Page Content Here</div>
   </div>
</div>
<!-- Insert Closing Tags Below-->

这篇关于在特定的HTML注释后插入HTML块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆