My HTML 开发者_Go百科and JavaScript code look like this:
<html>
<!--...
many code
...-->
<button onclick="alert($('#mytable').html().wrap('<html/>') );">Show HTML Table</button>
<table id="myTable">
<tr's and td's>
</table>
<!--...
many code
...-->
</html>
I want my javascript to return the table wrapped by the HTML tags but I do not want the table itself to be changed.
You could take a copy of the table first:
$('#mytable').clone()...
To get the actual HTML of the tag you'd need something like this plugin which I posted in another answer yesterday:
(function($) {
$.fn.outerhtml = function() {
return $('<div/>').append(this.clone()).html();
};
})(jQuery);
So you can then do:
alert('<html>' + $('#myTable').outerhtml() + '</html>');
See http://jsfiddle.net/alnitak/2y988/ for a working demo.
This does not work. .html()
returns a string, not a jQuery object. So you cannot call wrap
on it.
The other problem is that .html()
only returns the inner HTML, it does not include the table
tag.
You could .clone()
the node, attach it to some dummy element and return the .html()
:
var html = ['<html><body>',
$('<div/>').append($('#mytable').clone()).html(),
'</body></html>'].join('');
Maybe this jQuery outerHTML plugin will help you. It will give you the code for the table, including the enclosing <table>
tags. You can maybe do something like alert("<html>" + $("#myTable").outerHtml() + "</html>")
.
Why not just do the following?:
alert('<html>'+$('#mytable').html()+'</html>');
$("#myTable").wrap("...");
That will wrap the table in the tag supplied to the wrap
function, without altering the table
itself.
For more information, see the jQuery API for the wrap
function.
精彩评论