如何从 Jquery 获取完整的表格 html?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19667302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the full table html from Jquery?
提问by FlyingCat
I am trying to get the table html in Jquery.
我正在尝试在 Jquery 中获取表格 html。
I have the following:
我有以下几点:
<table id='table' border='1'>
<tr><td>items...</td><td>items2...</td></tr>
<tr><td>items...</td><td>items2...</td></tr>
<tr><td>items...</td><td>items2...</td></tr>
<tr><td>items...</td><td>items2...</td></tr>
</table>
I have
我有
var test = $('#table').html()
but when i console.log(test) i got
但是当我 console.log(test) 我得到了
<tr><td>items...</td><td>items2...</td></tr>
<tr><td>items...</td><td>items2...</td></tr>
<tr><td>items...</td><td>items2...</td></tr>
<tr><td>items...</td><td>items2...</td></tr>
without <table>
tags.
没有<table>
标签。
Is there anyway to fix this? Thanks a lot!
有没有什么办法解决这一问题?非常感谢!
回答by Stieffers
A more jQuery oriented approach would be to retrieve the outerHtml property from the table.
更面向jQuery 的方法是从表中检索outerHtml 属性。
$('#table').prop('outerHTML')
回答by David says reinstate Monica
One option is:
一种选择是:
document.getElementById('table').outerHTML;
Or, you could instead:
或者,您可以改为:
$('<div />').html($('#table').clone()).html();
回答by grammar
Another option is to wrap the table in something else, then get the html() of that element instead.
另一种选择是将表格包装在其他东西中,然后获取该元素的 html() 。
Example Markup:
示例标记:
<div class="wrapper">
<table id='table' border='1'>
<tr><td>items...</td><td>items2...</td></tr>
<tr><td>items...</td><td>items2...</td></tr>
<tr><td>items...</td><td>items2...</td></tr>
<tr><td>items...</td><td>items2...</td></tr>
</table>
</div>
And the jQuery:
和 jQuery:
var table = $('.wrapper').html();
You should probably just use @David Thomas' answer though.
不过,您可能应该只使用@David Thomas 的回答。