繁体   English   中英

javascript替代jquery html()

[英]Javascript alternative to jquery html()

你会怎么写这个jQuery方法

$('body').html(node); 

在Javascript中将html设置为节点?

谢谢

是的,这是可能的:

document.body.innerHTML="<h1>Hello World</h1>";

http://www.tizag.com/javascriptT/javascript-innerHTML.php

如果node是DOM节点而不是HTML字符串,则应该在innerHTML上使用DOM方法:

while (document.body.firstChild) {
    document.body.removeChild(document.body.firstChild);
}
document.body.appendChild(node);

请参阅MDC文档:

您正在寻找innerHTML属性:

document.getElementById("test").innerHTML = "";

document.body.innerHTML = 'my html here';

而对于更一般的情况而不仅仅是设置身体....

// replace a single element by its ID
// i.e. $("#myDivId")
var myDiv = document.getElementById("myDivId");
myDiv.innerHtml = "foo";

// replace all elements of a given tag name
// i.e. $("span")
var allSpanTags = document.getElementsByTagName("span");
allSpanTags[0].innerHtml = "foo"; // or loop over the array or whatever.

// by class name
// i.e. $(".myClass")
var allMyClass = document.getElementsByClassName("myClass");

作为参考,这是jquery的方式:

html: function( value ) {
    if ( value === undefined ) {
        return this[0] && this[0].nodeType === 1 ?
            this[0].innerHTML.replace(rinlinejQuery, "") :
            null;

    // See if we can take a shortcut and just use innerHTML
    } else if ( typeof value === "string" && !rnocache.test( value ) &&
        (jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
        !wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {

        value = value.replace(rxhtmlTag, "<$1></$2>");

        try {
            for ( var i = 0, l = this.length; i < l; i++ ) {
                // Remove element nodes and prevent memory leaks
                if ( this[i].nodeType === 1 ) {
                    jQuery.cleanData( this[i].getElementsByTagName("*") );
                    this[i].innerHTML = value;
                }
            }

        // If using innerHTML throws an exception, use the fallback method
        } catch(e) {
            this.empty().append( value );
        }

    } else if ( jQuery.isFunction( value ) ) {
        this.each(function(i){
            var self = jQuery( this );

            self.html( value.call(this, i, self.html()) );
        });

    } else {
        this.empty().append( value );
    }

    return this;
},

它尽可能使用innerHTML,但它也有一个回退方法。

如果是要插入HTML的正文标记,请尝试以下操作:

document.body.innerHTML = node;

要么

document.getElementsByTagName('body')[0].innerHTML = node;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM