你会如何编写这个jQuery方法?
在JavaScript中设置节点的HTML内容怎么做?谢谢。
$('body').html(node);
在JavaScript中设置节点的HTML内容怎么做?谢谢。
$('body').html(node);
是的,这是可能的:
document.body.innerHTML="<h1>Hello World</h1>";
如果node
是DOM节点而不是HTML字符串,您应该使用DOM方法而不是innerHTML
:
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
document.body.appendChild(node);
See MDC docs:
对于比仅设置正文更一般的情况...
// 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,但也具备备用方法。
document.body.innerHTML = node;
或者
document.getElementsByTagName('body')[0].innerHTML = node;
document.body.innerHTML = '我的 HTML 在这里';