Javascript - Div标签自动关闭

时间:2016-07-08 10:04:50

标签: javascript html css

我正在将我的网站更改为各种现代网络应用程序,这是我的HTML代码..

<joexn-profile>
<joexn-logo></joexn-logo>
<joexn-text></joexn-text>
</joexn-profile>

这是我用于<joexn-profile>代码的JavaScript。

var joexnprofile = document.querySelector('joexn-profile');
joexnprofile.insertAdjacentHTML( 'afterBegin', '<center><div class="joexn-profile">');
joexnprofile.insertAdjacentHTML( 'afterEnd', '</div></center>');

问题是,<div class="joexn-profile">标记会自动关闭。

看一下inspect元素视图:

enter image description here





仅限JavaScript

2 个答案:

答案 0 :(得分:1)

正如Quentin已经解释的那样,你不能只插入一半节点。

另一方面,你为什么要这样做呢?

第一:避免像<center><font><b>这样的标签,......如果你想要样式......用CSS做。

和第二:用<joexn-profile>取代<div class="joexn-profile">有什么意义?
您应用于.joexn-profile CSS-Selector的每种样式也可以应用于joexn-profile CSS-Selector。

唯一的区别是,您必须为display:block声明joexn-profile,以便浏览器知道如何呈现此节点; blockinline或其他。

但如果你坚持按照自己的方式行事,这里有一个小工具可以处理html-markup(甚至部分)和DON-Nodes的组合。

免责声明:代码未经过全面测试,可能仍会包含错误。并且fragment()不处理循环引用!

https://jsfiddle.net/mkapLz1k/1/

//just to be clear: this ain't a replacement for jQuery, nor does it interfere with it's purposes.
//it's a set of utilities to enable working with compositions of HTML-Markup and plain DOM-Nodes
var nodeUtils = (function(){
    var container = document.createElement("div"), 
        placeholder = document.createElement("div"),
        forEach = Array.prototype.forEach;

    function _replacePlaceholder(node){
        var parent = node.parentNode;
        parent.insertBefore(this[node.id], node);
        parent.removeChild(node);
    }

    function _randomId(){
        return ("id"+Math.random()+Math.random()+Math.random()).replace(/0\./g, "-")
    }

    function _fragment(src){
        var markup = [], 
            nodesById = {}, 
            id = "", 
            ids = [];

        function _addNode(node){
            if(!id){
                nodesById[id=_randomId()] = fragment();
                ids.push("#"+id);
                //add placeholder into the html-markup.
                //These placeholder get eventually replaced.
                markup.push('<div id="'+id+'"></div>');
            }
            nodesById[id].appendChild( node );
        }

        function _parse(node){
            if(node == null || node === "" || typeof node === "function") return;

            if(typeof node === "object"){
                if("nodeType" in node){
                    //processes DOM Nodes, of all shapes and sizes ;)
                    //including Comment-Nodes, TextNodes and DocumentFragments, ...
                    _addNode( node );
                }else if(this.NodeList && node instanceof NodeList){
                    //nodeLists change
                    //so I have to process them differently than regular lists
                    while(node.length) _addNode( node[0] );
                }else{
                    //processes anything ArrayLike
                    for(var i = 0, len = ("length" in node && node.length)|0; i<len; ++i)
                        i in node && _parse( node[i] );
                }
            }else{
                //processes primitives as html-markup
                id = "";
                markup.push( node );
            }
        }

        _parse( src );

        if(ids.length === markup.length){ //=> 0 or 1
            //src contained only Nodes, no strings or primitives
            return id? nodesById[id]: void 0;
        }

        //src contained html-markup that needs to be parsed
        container.innerHTML = markup.join("");
        if(ids.length){
            //injecting the DOM-Nodes
            forEach.call( container.querySelectorAll( ids.join(",") ), _replacePlaceholder, nodesById );
        }

        for(var frag = fragment(), fc; fc = container.firstChild; )
            frag.appendChild( fc );
        return frag;
    }


    //`fragment()` is shorthand for `document.createDocumentFragment()`
    //`fragment(composition)` returns a DocumentFragment, that can be used with `node.appendChild()`.

    //takes an arbitrary composition of nested Arrays (or ArrayLike-structures, like jQuery-Objects, NodeLists, ...), containing DOM-Nodes or strings/primitives and builds a DocumentFragment out of that
    function fragment(composition){
        return composition != null && _fragment(composition) || document.createDocumentFragment();
    }


    //all the following functions can take anything that `fragment()` can handle as input:
    //only `node` has to be a real DOM-Node!

    //almost like setting a Nodes innerHTML, but it takes more than just HTML-Markup
    function content(node, composition){
        for(var frag = fragment(composition), fc; fc=node.firstChild;) node.removeChild(fc);
        node.appendChild(frag);
        return node;
    }

    //replace a Node with the provided 
    function replace(node, composition){
        var parent = node.parentNode;

        parent.insertBefore(placeholder, node);
        parent.insertBefore(fragment(composition), placeholder);
        parent.removeChild(placeholder);

        //how parent could have changed? maybe you referenced node somewhere in composition.
        if(parent === node.parentNode) parent.removeChild(node);

        return node;
    }

    //wraps a Node in the provided markup.
    //beforeBegin and afterEnd CAN contain associated markup. Like opening and closing Tag of the same Node.
    //e.g.: wrapNode(node, "<div>", "</div>");
    function wrapNode(node, beforeBegin, afterEnd){
        return replace(node, [beforeBegin, node, afterEnd]);
    }

    //wraps the content of the node in the provided Markup.
    //afterBegin and beforeEnd CAN contain associated markup. Like opening and closing Tag of the same Node.
    function wrapContent(node, afterBegin, beforeEnd){
        node.appendChild(fragment([afterBegin, node.childNodes, beforeEnd]));
        return node;
    }

    return {
        fragment: fragment,
        replace: replace,
        wrapNode: wrapNode,
        wrapContent: wrapContent,
        content: content,
    }   
})();

和你的标记:

var joexnprofile = document.querySelector('joexn-profile');

//telling by your code, it's not entirely clear 
//wich of these you actually want to do:

nodeUtils.wrapNode(
    joexnprofile,
    '<center><div class="joexn-profile">',
    '</div></center>'   
);

//or
nodeUtils.wrapContent(
    joexnprofile,
    '<center><div class="joexn-profile">',
    '</div></center>'   
);

//or maybe
nodeUtils.replace(
    //replace this:
    joexnprofile, 

    //with this:
    [
        '<center><div class="joexn-profile">',
        joexnprofile.childNodes,
        '</div></center>'
    ]
);

看看代码示例,您就可以了解fragment()能够处理的内容

var frag = nodeUtils.fragment([ 
    //you can build this Array inline, no need to do that beforehand
    condition? 
        window.title: 
        //simply inject `null` or `undefined` or `""` and this entry will be ignored
        null,

    //nest Arrays, they get parsed recursively
    [
        //mix (partial) HTML with other types
        '<div class="columns">',
            //real Nodes in the middle of some Markup: check
            document.getElementById('leftColumn'),

            //even more nesting, no problem
            [
                '<div class="middle">', 

                //handles anything Arraylike that contains Nodes or Markup
                jQuery('.someClass'),

                "</div>"
            ]
        '</div>'
    ],

    //NodeLists, no Problem
    document.querySelectorAll("#footer > div")
])

现在由您决定如何使用它。

答案 1 :(得分:0)

尽管insertAdjacentHTML提供了抽象,但您仍在使用DOM。它具有严格的层次结构中的元素,它没有开始和结束标记。

HTML将转换为DOM节点并插入。您没有编辑原始源代码。

请改用createElement。使用querySelector在新元素中获取所需元素,然后使用appendChild将其移动到新元素中。

相关问题