[英]How to return the result without altering the source?
My HTML and JavaScript code look like this:我的 HTML 和 JavaScript 代码如下所示:
<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.我希望我的 javascript 返回由 HTML 标记包装的表,但我不希望表本身被更改。
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 :要获得标签的实际 HTML,您需要类似于我昨天在另一个答案中发布的这个插件:
(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.有关工作演示,请参阅http://jsfiddle.net/alnitak/2y988/ 。
This does not work.这不起作用。
.html()
returns a string, not a jQuery object. .html()
返回一个字符串,而不是 jQuery object。 So you cannot call wrap
on it.所以你不能调用
wrap
。
The other problem is that .html()
only returns the inner HTML , it does not include the table
tag.另一个问题是
.html()
只返回内部 HTML ,它不包含table
标记。
You could .clone()
the node, attach it to some dummy element and return the .html()
:您可以
.clone()
节点,将其附加到一些虚拟元素并返回.html()
:
var html = ['<html><body>',
$('<div/>').append($('#mytable').clone()).html(),
'</body></html>'].join('');
Maybe this jQuery outerHTML plugin will help you.也许这个jQuery outerHTML 插件会对您有所帮助。 It will give you the code for the table, including the enclosing
<table>
tags.它将为您提供表格的代码,包括封闭的
<table>
标记。 You can maybe do something like alert("<html>" + $("#myTable").outerHtml() + "</html>")
.你也许可以做类似
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.这会将表格包装在提供给
wrap
function 的标签中,而不会更改table
本身。
For more information, see the jQuery API for the wrap
function.有关详细信息,请参阅jQuery API以了解
wrap
function。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.