我有一个div:
<div id="contract"></div>
它由JQuery使用来自客户端javascript和数据( innerHTML )的字符串填充,这些字符串来自我的服务器:
$('#submit').click(function () {
document.getElementById('contract').innerHTML = 'foobar';
var profile = $('#profile').val();
var query = {
'profile': profile
};
$.get('/foo/profileViewer', query, function (data) {
var result = $.parseJSON(data);
document.getElementById('contract').innerHTML += result ; //$('#contract').html(result); doesn't work either
})
});
我只想打印contract
div
。
我尝试了JQuery答案建议的here和here,并且都指向了div
已经包含了HTML文本的答案,而不是从服务器获得的内容。奇怪的是,如果我删除$.get
并实现所提供的答案之一,"foobar"
确实会打印。如果我不删除$.get
,nothing就会打印出来。我尝试使用$.ajax
而不是$.get
,但这并不能解决问题。我尝试使用CSS解决方案here,但这会扰乱来自服务器端的数据(HTML),因为它已经将CSS分页媒体嵌入其中。因此,我不想使用CSS解决方案。
如果JQuery包含从服务器端获取的数据,请有人建议我使用div
打印div
的好方法吗?
发布于 2015-12-10 16:24:56
尝试使用隐藏的iframe:
$('#submit').click(function (e) {
e.preventDefault();
$('#contract').empty();
var profile = $('#profile').val();
var query = {
profile: profile
};
$.get('/foo/profileViewer', query, function (data) {
$('body').append('<iframe id="printf" style="display:none;" name="printf"></iframe>');
$('#printf').contents().find('body').append(data);
window.frames["printf"].focus();
window.frames["printf"].print();
})
});
发布于 2015-12-10 16:17:50
走这条路
$('#contract').text(JSON.stringify(data));
或
$('#contract').append(
$('<pre>').text(
JSON.stringify(data, null, ' ')
)
)
发布于 2015-12-10 16:25:33
您不能直接打印标签,.But这个技巧可以帮助:
<script language="javascript" type="text/javascript">
function printDiv(divID) {
//Get the HTML of div
var divElements = document.getElementById(divID).innerHTML;
//Get the HTML of whole page
var oldPage = document.body.innerHTML;
//Reset the page's HTML with div's HTML only
document.body.innerHTML =
"<html><head><title></title></head><body>" +
divElements + "</body>";
//Print Page
window.print();
//Restore orignal HTML
document.body.innerHTML = oldPage;
}
</script>
https://stackoverflow.com/questions/34206638
复制相似问题