When using jQuery to dynamically build markup, it sometimes becomes useful to have it开发者_开发知识库 return the actual HTML that it's generating as a string, rather than as a bunch of jQuery objects. Is there a way to do this? For example, here:
$("<strong></strong>").text("Hi there!");
I want to be able to extract the plain-text string
"<strong>Hi there!</strong>"
so that I can cache it remotely. Is there a way to do this?
Yes, you can use the html() function
i.e.
$("").text("Hi There!").html();
Will return 'Hi There!'
Keep in mind this uses innerHTML, so
$("<div><b>Foo</b></div>").html();
will return
<b>Foo</b>
As a result you'll need to wrap your code in a surrounding div or span.
You can use a outerHTML plugin for that. Here is one:
jQuery.fn.outerHTML = function(s) {
return (s)
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
}
Usage:
alert($("<strong></strong>").text("foo").outerHTML());
// alerts <strong>foo</strong>
Just call .html() to get HTML from any element, including generated ones. This is from a Chrome developer tool session:
> $("<div><span>blerg</span></div>")
Object
> $("<div><span>blerg</span></div>").html()
<span>blerg</span>
You can see, the first one returned an object, the second returns text.
精彩评论